如果我有一些任意的 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" }
}
}
}]
}
我想获取位于 data.0.links.author.linkage.id
的字符串 "9"
,使用如下内容:
[]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{} 中做 deep sets 和 gets?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29298645/