Essential Go JSON  Edit on GitHub      File Issue

Decoding JSON from a file

We can decode JSON data from a file on disk or, more broadly, any io.Reader, like a network connection.

Let’s assume we have a file called data.json with the following content:

[
    {
        "Name" : "John Doe",
        "Standard" : 4
    },
    {
        "Name" : "Peter Parker",
        "Standard" : 11
    },
    {
        "Name" : "Bilbo Baggins",
        "Standard" : 150
    }
]

The following example reads the file and decodes the content:

type Student struct {
	Name     string
	Standard int `json:"Standard"`
}

func decodeFromReader(r io.Reader) ([]*Student, error) {
	var res []*Student

	dec := json.NewDecoder(r)
	err := dec.Decode(&res)
	if err != nil {
		return nil, err
	}
	return res, nil
}

func decodeFromString(s string) ([]*Student, error) {
	r := bytes.NewBufferString(s)
	return decodeFromReader(r)
}

func decodeFromFile(path string) ([]*Student, error) {
	f, err := os.Open(path)
	if err != nil {
		return nil, err
	}
	defer f.Close()
	return decodeFromReader(f)
}
Student: John Doe, standard: 4
Student: Peter Parker, standard: 11
Student: Bilbo Baggins, standard: 150

By writing a helper function decodeFromReader, we can easily write wrappers that will work on files, strings or network connections.

  ↑ ↓ to navigate     ↵ to select     Esc to close