How to make deep sets and get in Go map [string] interface {}?

If I have some kind of arbitrary JSON, how can I do deep sets and fall into nested properties using a piece of map keys and / or slice indices?

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 would like to get the string "9" located in data.0.links.author.linkage.id , using something like:

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

I know that the ideal way to do this is to create nested structures that map to the JSON object that I am doing for production code, but sometimes I need to do a little testing, which would be nice to do in Go too.

+2
source share
1 answer

You have stretchr/objx that provide a similar approach.

Usage example:

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

However, if you really don’t know at all the structure of your JSON input ahead of time, this is not the most preferred way to go to golang ...

+3
source

Source: https://habr.com/ru/post/1216522/


All Articles