How can I do a json.Unmarshal from a .json file?

So I’m learning ways to use json data, so for A) I have hardcoded the .json data and it works, but when I try to read the same data but from a .json file (B), it executes but nothing prints.

A)

 text := "[{\"Id\": 100, \"Name\": \"Go\"}, {\"Id\": 200, \"Name\": \"Java\"}]"
 bytes := []byte(text)
 
 var boxes []Box
 json.Unmarshal (bytes, &boxes)

 for i := range boxes {
 	fmt.Printf("Id = %v, Name = %v", boxes[i].Id, boxes[i].Name)
 	fmt.Println()
 }

/* Output:
Id = 100, Name = Go
Id = 200, Name = Java
*/

B)

bytes, _ := ioutil.ReadFile("file.json")

var boxes []Box
json.Unmarshal (bytes, &boxes)

for i := range boxes {
fmt.Printf("Id = %v, Name = %v", boxes[i].Id, boxes[i].Name)
fmt.Println()
}

I’m fairly new to Go so any help/tips/corrections will be appreciated.

You’re ignoring errors. Never do that. As it is, you don’t know if ioutil.ReadFile succeeds or not, or if the json.Unmarshal fails.

3 Likes
f, err := os.Open(...)
if err != nil {
       log.Fatal(err)
}
d := json.NewDecoder(f)
var boxes []Box
err = d.Decode(&boxes)
if err != nil {
       log.Fatal(err)
}
7 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.