Logo

Programming-Idioms

History of Idiom 91 > diff from v3 to v4

Edit summary for version 4 by :

Version 3

2015-09-24, 12:02:15

Version 4

2015-09-24, 12:03:43

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 := ioutil.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
Demo URL
http://play.golang.org/p/hLL7i07gf1
Demo URL
http://play.golang.org/p/FPA64xk7m-