英文:
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…
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论