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

huangapple go评论95阅读模式
英文:

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

问题

如果我有一些任意的 JSON 数据,如何使用一组映射键和/或索引切片对嵌套属性进行深度设置和获取?

例如,在以下摘录中来自 JSON API 示例

{
    "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" }
            }
        }
    }]
}

我想要获取位于 data.0.links.author.linkage.id 的字符串 "9",类似于以下方式:

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

我知道理想的方法是创建映射到 JSON 对象的嵌套结构体,这是我在生产代码中做的,但有时我需要进行一些快速测试,希望也能在 Go 中完成。

英文:

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.

答案1

得分: 4

你有stretchr/objx这个库提供了类似的方法。

示例用法:

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

然而,除非你完全不知道 JSON 输入的结构,否则这不是在 Golang 中首选的方法...

英文:

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…

huangapple
  • 本文由 发表于 2015年3月27日 18:36:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/29298645.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定