Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can we read a json file as json object in golang

Tags:

I have a JSON file stored on the local machine. I need to read it in a variable and loop through it to fetch the JSON object values. If I use the Marshal command after reading the file using the ioutil.Readfile method, it gives some numbers as an output. These are my few failed attempts,

Attempt 1:

plan, _ := ioutil.ReadFile(filename) // filename is the JSON file to read var data interface{} err := json.Unmarshal(plan, data) if err != nil {         log.Error("Cannot unmarshal the json ", err)       } fmt.Println(data) 

It gave me following error,

time="2016-12-13T22:13:05-08:00" level=error msg="Cannot unmarshal the json json: Unmarshal(nil)" <nil> 

Attempt 2: I tried to store the JSON values in a struct and then using MarshalIndent

generatePlan, _ := json.MarshalIndent(plan, "", " ") // plan is a pointer to a struct fmt.Println(string(generatePlan)) 

It give me the output as string. But if I cast the output to string then I won't be able to loop it as JSON object.

How can we read a JSON file as JSON object in golang? Is it possible to do that? Any help is appreciated. Thanks in advance!

like image 234
Aishwarya Avatar asked Dec 14 '16 05:12

Aishwarya


People also ask

How do I write JSON data to a file in Golang?

The struct values are initialized and then serialize with the json. MarshalIndent() function. The serialized JSON formatted byte slice is received which then written to a file using the ioutil. WriteFile() function.

Can you write JSON file using Go language?

Reading and Writing JSON Files in GoIt is actually pretty simple to read and write data to and from JSON files using the Go standard library. For writing struct types into a JSON file we have used the WriteFile function from the io/ioutil package. The data content is marshalled/encoded into JSON format.


1 Answers

The value to be populated by json.Unmarshal needs to be a pointer.

From GoDoc :

Unmarshal parses the JSON-encoded data and stores the result in the value pointed to by v.

So you need to do the following :

plan, _ := ioutil.ReadFile(filename) var data interface{} err := json.Unmarshal(plan, &data) 

Your error (Unmarshal(nil)) indicates that there was some problem in reading the file , please check the error returned by ioutil.ReadFile


Also please note that when using an empty interface in unmarshal, you would need to use type assertion to get the underlying values as go primitive types.

To unmarshal JSON into an interface value, Unmarshal stores one of these in the interface value:

bool, for JSON booleans float64, for JSON numbers string, for JSON strings []interface{}, for JSON arrays map[string]interface{}, for JSON objects nil for JSON null 

It is always a much better approach to use a concrete structure to populate your json using Unmarshal.

like image 170
John S Perayil Avatar answered Sep 16 '22 14:09

John S Perayil