JSON和Golang的无限结构

时间:2018-11-20 14:59:29

标签: json go

我不知道如何用Golang解组这种JSON结构。键是动态的,嵌套键和值也是动态的。

{"key1":{"col1":"Data11","col2":"Data12","col3":"Data13","col4":"Data14"},
 "key2":{"col1":"Data21","col2":"Data22","col3":"Data23","col4":"Data24"},
 "key3":{"col1":"Data31","col2":"Data32","col3":"Data33","col4":"Data34"},
 "key4":{"col1":"Data41","col2":"Data42","col3":"Data43","col4":"Data44"},
 "key5":{"col1":"Data51","col2":"Data52","col3":"Data53","col4":"Data54"},
 "key6":{"col1":"Data61","col2":"Data62","col3":"Data63","col4":"Data64"}}

我被困住了。

1 个答案:

答案 0 :(得分:1)

您需要将数据解组到map [string] map [string] string中,如下所示:

jsonData:="{\"key1\":{\"col1\":\"Data11\",\"col2\":\"Data12\",\"col3\":\"Data13\",\"col4\":\"Data14\"}, \"key2\":{\"col1\":\"Data21\",\"col2\":\"Data22\",\"col3\":\"Data23\",\"col4\":\"Data24\"}, \"key3\":{\"col1\":\"Data31\",\"col2\":\"Data32\",\"col3\":\"Data33\",\"col4\":\"Data34\"}, \"key4\":{\"col1\":\"Data41\",\"col2\":\"Data42\",\"col3\":\"Data43\",\"col4\":\"Data44\"}, \"key5\":{\"col1\":\"Data51\",\"col2\":\"Data52\",\"col3\":\"Data53\",\"col4\":\"Data54\"}, \"key6\":{\"col1\":\"Data61\",\"col2\":\"Data62\",\"col3\":\"Data63\",\"col4\":\"Data64\"}}"
    var jsonObject map[string]map[string]string
    json.Unmarshal([]byte(jsonData),&jsonObject)
    for k:=range jsonObject{
        fmt.Println(k ," has " , len(jsonObject[k]) , " fields")
        for j:=range jsonObject[k]{
            fmt.Println(j , "=",jsonObject[k][j] )
        }
    }