Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

json unmarshalling without struct

Tags:

json

go

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

like image 660
user2727195 Avatar asked May 03 '17 21:05

user2727195


2 Answers

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

like image 148
codyoss Avatar answered Sep 20 '22 15:09

codyoss


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
}
like image 34
Rolas Avatar answered Sep 21 '22 15:09

Rolas