Logo

Programming-Idioms

History of Idiom 91 > diff from v17 to v18

Edit summary for version 18 by programming-idioms.org:
[Go] Better demo with raw string literal

Version 17

2016-02-18, 16:58:02

Version 18

2016-04-28, 11:42:28

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/FPA64xk7m-
Demo URL
https://play.golang.org/p/lGZ4vuDKH6