我想在Golang中使用JSON,特别是弹性搜索JSON协议。
JSON是深度嵌套的(这是一个简单的查询):
{
"query": {
"filtered": {
"query": {
"match_all": {}
},
"filter": {
"and": [
{
"range" : {
"b" : {
"from" : 4,
"to" : "8"
}
},
},
{
"term": {
"a": "john"
}
}
]
}
}
}
}这种结构很容易映射到Ruby中的原生数据结构。
但是使用Golang,您似乎必须使用struct定义确切的结构(也许可以从JSON源代码以编程方式生成它们)。
即便如此,像JS中对象的不同“类型”的数组这样的东西也需要解决办法和自定义代码。例如,示例JSON中的"and“键。(http://mattyjwilliams.blogspot.co.uk/2013/01/using-go-to-unmarshal-json-lists-with.html)。
在Golang中有更好的方式使用JSON吗?
发布于 2015-08-04 14:22:27
如果您选择使用struct路由,请考虑以下示例:
{"data": {"children": [
{"data": {
"title": "The Go homepage",
"url": "http://golang.org/"
}},
...
]}}
// -----------
type Item struct {
Title string
URL string
}
type Response struct {
Data struct {
Children []struct {
Data Item
}
}
}来源:http://talks.golang.org/2012/10things.slide#4
发布于 2016-11-04 01:39:25
其中一个选项是使用gabs库:https://github.com/Jeffail/gabs
它对于解析和生成复杂的json结构非常有用。
这是从自述文件生成嵌套json的示例:
jsonObj := gabs.New()
// or gabs.Consume(jsonObject) to work on an existing map[string]interface{}
jsonObj.Set(10, "outter", "inner", "value")
jsonObj.SetP(20, "outter.inner.value2")
jsonObj.Set(30, "outter", "inner2", "value3")将打印:
{"outter":{"inner":{"value":10,"value2":20},"inner2":{"value3":30}}}https://stackoverflow.com/questions/31797892
复制相似问题