json - 如何使用 Go unmarshal 解析复杂的 JSON?

标签 json parsing go

go 标准包encoding/json公开 json.Unmarshal 函数来解析 JSON。

可以在预定义的 struct 中解码 JSON 字符串,或者使用 interface{} 并为意外的 JSON 数据结构迭代结果。

也就是说,我无法正确解析复杂的 JSON。谁能告诉我如何实现这一目标?

 {
     "k1" : "v1", 
     "k2" : "v2", 
     "k3" : 10, 
     "result" : [
                 [
                 ["v4", v5, {"k11" : "v11", "k22" : "v22"}]
                 , ... , 
                 ["v4", v5, {"k33" : "v33", "k44" : "v44"}
                 ]
                 ], 
                 "v3"
                ] 
}

最佳答案

引自 JSON and Go :

Without knowing this data's structure, we can decode it into an interface{} value with Unmarshal:

b := []byte(`{
   "k1" : "v1", 
   "k3" : 10,
   result:["v4",12.3,{"k11" : "v11", "k22" : "v22"}]
}`)
var f interface{}
err := json.Unmarshal(b, &f)

At this point the Go value in f would be a map whose keys are strings and whose values are themselves stored as empty interface values:

f = map[string]interface{}{
    "k1": "v1",
    "k3":  10,
    "result": []interface{}{
       "v4",
       12.3,
       map[string]interface{}{
           "k11":"v11",
           "k22":"v22",
       },
    },
}

To access this data we can use a type assertion to access f's underlying map[string]interface{}:

m := f.(map[string]interface{})

We can then iterate through the map with a range statement and use a type switch to access its values as their concrete types:

for k, v := range m {
    switch vv := v.(type) {
    case string:
        fmt.Println(k, "is string", vv)
    case int:
        fmt.Println(k, "is int", vv)
    case []interface{}:
        fmt.Println(k, "is an array:")
        for i, u := range vv {
            fmt.Println(i, u)
        }
    default:
        fmt.Println(k, "is of a type I don't know how to handle")
    }
}

In this way you can work with unknown JSON data while still enjoying the benefits of type safety.

有关 Go 和 JSON 的更多信息可以在原始文章中找到。我稍微更改了代码片段,使其更类似于问题中的 JSON。

关于json - 如何使用 Go unmarshal 解析复杂的 JSON?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30341588/

相关文章:

go - 枚举作为变量的属性

json - 如何在 Golang 中获取 JSON 唯一字段的名称和深度嵌套的子字段的值?

json - 使用 serde_json 解析对象内部的对象

javascript - 我无法访问数组中的对象,即使它存在

java - 从 ANTLR 中的语法规则调用方法?

javascript - 这个语法怎么有歧义?

javascript - 在 javascript 中检索 JSON 数据时出现问题

java - 在我的 gridview 数组中使用 json 数据

Java 和 Excel : value being read wrong

go - 数据竞赛无法理解