doutusheng5879 2015-05-20 06:11
浏览 807
已采纳

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

In go the standard package encoding/json exposes json.Unmarshal function to parse JSON.

It's possible to either unmarshal the JSON string in a predefined struct, or use the interface{} and iterate the result for unexpected JSON data structure.

That said, I can't parse complex JSON properly. Can someone tell me how to achieve this?

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

3条回答 默认 最新

  • douzhan1238 2015-05-20 06:32
    关注

    Citing from 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.

    More information about Go and JSON can be found in the original article. I changed the code snippets slightly to be more similar to the JSON in the question.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?