如果我有一些任意的JSON,我该如何使用 slice 键和/或 slice 索引进行深度设置并获取嵌套属性?

例如,在下面的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" }
            }
        }
    }]
}

我想使用类似以下的方式获取位于"9"的字符串data.0.links.author.linkage.id:
[]interface{}{"data",0,"links","author","linkage","id"}

我知道执行此操作的理想方法是创建嵌套结构,该结构映射到我为生产代码执行的JSON对象,但是有时我需要进行一些快速测试,这同样适用于Go。

最佳答案

您拥有提供类似方法的 stretchr/objx

使用示例:

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

但是,除非您真的真的完全不知道JSON输入的结构,否则这不是进入golang的首选方式…

关于json - 如何在Go的map [string] interface {}中进行深层设置和获取?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29298645/

10-11 09:18
查看更多