Decoding JSON from a file

suggest change

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

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.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents