Logo

Programming-Idioms

History of Idiom 91 > diff from v1 to v2

Edit summary for version 2 by :

Version 1

2015-09-17, 20:57:32

Version 2

2015-09-17, 20:59:13

Idiom #91 Load JSON file into struct

Read from file data.json and write its content into object x.
Assume the JSON data is suitable for the type of x.

Idiom #91 Load JSON file into struct

Read from file data.json and write its content into object x.
Assume the JSON data is suitable for the type of x.

Imports
import "encoding/json"
import "io/ioutil"
Imports
import "encoding/json"
import "io/ioutil"
Code
buffer, err := ReadFile("data.json")
if err != nil {
	return err
}
err := json.Unmarshal(buffer, &x)
if err != nil {
	return err
}
Code
buffer, err := ioutil.ReadFile("data.json")
if err != nil {
	return err
}
err = json.Unmarshal(buffer, &x)
if err != nil {
	return err
}
Comments bubble
buffer is a []byte.
&x is the address of x.
You must check errors after each step.
Comments bubble
buffer is a []byte.
&x is the address of x.
You must check errors after each step.
Doc URL
http://golang.org/pkg/encoding/json/#Unmarshal
Doc URL
http://golang.org/pkg/encoding/json/#Unmarshal