简体   繁体   中英

How to do deep sets and gets in Go's map[string]interface{}?

If I have some arbitrary JSON how can I do deep sets and gets on the nested properties using a slice of map keys and/or slice indexes?

For example, in the following excerpt from the JSON API example :

{
    "data": [{
        "type": "posts",
        "id": "1",
        "title": "JSON API paints my bikeshed!",
        "links": {
            "self": "http://example.com/posts/1",
            "author": {
                "self": "http://example.com/posts/1/links/author",
                "related": "http://example.com/posts/1/author",
                "linkage": { "type": "people", "id": "9" }
            }
        }
    }]
}

I'd like to get the string "9" located at data.0.links.author.linkage.id using something like:

[]interface{}{"data",0,"links","author","linkage","id"}

I know the ideal way to do this is to create nested structs that map to the JSON object which I do for production code, but sometimes I need to do some quick testing which would be nice to do in Go as well.

You have stretchr/objx that provide a similar approach.

Example use:

document, _ := objx.FromJSON(json)
document.Get("path.to.field[0].you.want").Str()

However, unless you really don't know at all the structure of your JSON input ahead of time, this isn't the preferred way to go in golang…

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM