'json unmarshalling without struct
I've following json
[{"href":"/publication/192a7f47-84c1-445e-a615-ff82d92e2eaa/article/b;version=1493756861347"},{"href":"/publication/192a7f47-84c1-445e-a615-ff82d92e2eaa/article/a;version=1493756856398"}]
Based on the given answer I've tried following
var objmap map[string]*json.RawMessage
err := json.Unmarshal(data, &objmap)
I'm getting empty array with following error. any suggestions?
json: cannot unmarshal array into Go value of type map[string]*json.RawMessage
Solution 1:[1]
You can unmarshall to a []map[string]interface{} as follows:
data := []byte(`[{"href":"/publication/192a7f47-84c1-445e-a615-ff82d92e2eaa/article/b;version=1493756861347"},{"href":"/publication/192a7f47-84c1-445e-a615-ff82d92e2eaa/article/a;version=1493756856398"}]`)
var objmap []map[string]interface{}
if err := json.Unmarshal(data, &objmap); err != nil {
log.Fatal(err)
}
fmt.Println(objmap[0]["href"]) // to parse out your value
To see more on how unmarshalling works see here: https://godoc.org/encoding/json#Unmarshal
Solution 2:[2]
This is not direct answer but I think very useful
Json Unmarshal & Indent without struct
func JsonIndent (jsontext []byte) ([]byte,error) {
var err error
var jsonIndent []byte
var objmap map[string]*json.RawMessage
err = json.Unmarshal(jsontext, &objmap)
if err != nil {
return jsonIndent,err
}
jsonIndent, err = json.MarshalIndent(objmap,"", " ")
return jsonIndent,err
}
Solution 3:[3]
Your json is an array of objects, in Go the encoding/json package marshals/unmarshals maps to/from a json object and not an array, so you might want to allocate a slice of maps instead.
var objs []map[string]*json.RawMessage
if err := json.Unmarshal([]byte(data), &objs); err != nil {
panic(err)
}
https://play.golang.org/p/3lieuNkoUU
If you don't want to use a slice you can always wrap your json array in an object.
var dataobj = `{"arr":` + data + `}`
var objmap map[string]*json.RawMessage
if err := json.Unmarshal([]byte(dataobj), &objmap); err != nil {
panic(err)
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | M4C4R |
| Solution 2 | Rolas |
| Solution 3 |
