3

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.

Grokify
  • 15,092
  • 6
  • 60
  • 81
  • 3
    This can be done with 2 simple helper functions which I proposed [here in this answer](http://stackoverflow.com/a/28878037/1705598). – icza Mar 27 '15 at 10:39
  • Thanks icza! That's what I'm looking for. I'll try it out soon. As mentioned, this is only for quick debugging. For production code, I do create structs mapping to the JSON object. – Grokify Mar 27 '15 at 16:04
  • 1
    I also created a library doing exactly this: [github.com/icza/dyno](https://github.com/icza/dyno) – icza Dec 19 '17 at 16:12

1 Answers1

4

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…

Elwinar
  • 9,103
  • 32
  • 40
  • This approach isn't for production use where I do create structs that map to the JSON structure. This is mostly for quick debugging code that I'm probably not going to use again. – Grokify Mar 27 '15 at 16:02
  • 1
    Thanks Elwinar. I'll check this out. This is close as the `Get` function takes a single selector string but would be nice to automate creation of the string from a slice, e.g. `[]interface{}{"data",0,"links","author","linkage","id"}`. Might be worth a pull request. – Grokify Mar 28 '15 at 15:09