How to parse a complicated JSON with Go unmarshal?

前端 未结 3 984
小鲜肉
小鲜肉 2020-12-30 08:55

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

It\'s possible to either unmarshal the JSON string

3条回答
  •  遥遥无期
    2020-12-30 09:02

    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.

提交回复
热议问题