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

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.

Leave a Comment

tech