在Golang中使用嵌套JSON结构的最佳方法是什么?

zin*_*ino 7 json go

我喜欢在Golang中使用JSON,特别是弹性搜索JSON协议.

JSON是深层嵌套的(这是一个简单的查询):

{
    "query": {
        "filtered": {
            "query": {
                "match_all": {}
            },
            "filter": {
                "and": [
                    {
                        "range" : {
                            "b" : { 
                                "from" : 4, 
                                "to" : "8"
                            }
                        },
                    },
                    {
                        "term": {
                            "a": "john"
                        }
                    }
                ]
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

此结构可轻松映射到Ruby中的本机数据结构.

但是对于Golang,似乎你必须使用结构定义确切的结构(可能是从JSON源以编程方式生成它们).

即便如此,JS中不同"类型"对象的数组也需要解决方法和自定义代码.例如,示例JSON中的"和"键.(http://mattyjwilliams.blogspot.co.uk/2013/01/using-go-to-unmarshal-json-lists-with.html).

有没有更好的方法在Golang中使用JSON?

Bro*_*bay 5

如果您选择采用 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
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

资料来源:http ://talks.golang.org/2012/10things.slide#4


Jia*_* YD 1

对于原生 golang,使用map[string]interface{}或定义一个结构体。对于轻松访问 json 对象的其他方式,可能是JsonPathJason