Json在golang中解码/解组

时间:2016-04-07 05:09:51

标签: json go unmarshalling

我有以下json:

{"results":
[{"columns":["room_id","player_name","player_ip"],
  "types":["integer","text","text"],
  "values":[[1,"alice","127.0.0.1"]
            [1,"bob","127.0.0.1"]],
  "time":0.00018839100000000002}]}

其中值可以包含任意数量的元素[]。当我试图将json解组成一个结构时,"值"标签无法正确解析

结构:

type queryResults struct {
        Results []struct {
            Columns []string `json:"columns"`
            Types []string `json:"types"`
            Values []struct {
                Room_id int
                Player_name string
                Player_ip string
            } `json:"values"`
            Time float64 `json:"time"`
        } `json:"results"`
    }

代码:

//jsonString is the string input to Unmarshal
resultjson := queryResults{}
json.Unmarshal([]byte(jsonString), &resultjson)
fmt.Printf("%+v",resultjson)

当前输出:

{Results:
 [{Columns:[room_id player_name player_ip] 
   Types:[integer text text] 
   Values:[{room_id:0 player_name: player_ip:} 
           {room_id:0 player_name: player_ip:}] 
   Time:0.00018839100000000002}]}

预期产出:

{Results:
     [{Columns:[room_id player_name player_ip] 
       Types:[integer text text] 
       Values:[{room_id:1 player_name:alice player_ip:127.0.0.1} 
               {room_id:1 player_name:bob player_ip:127.0.0.1}] 
       Time:0.00018839100000000002}]}

2 个答案:

答案 0 :(得分:2)

问题是你的结构定义需要"值"包含一个对象数组,但实际的json包含一个数组数组。如果你检查json.Unmarshal()的结果,你会看到它报告错误。试试golang playground

error json: cannot unmarshal array into Go value of type struct { Room_id int; Player_name string; Player_ip string }

据我所知,您无法将其直接映射到结构中,您需要将其读入数组,然后将其处理为最终类型。这里有成功解析json的example [后解析转换留给读者练习]

{Results:[{Columns:[room_id player_name player_ip] 
          Types:[integer text text] 
          Values:[[1 alice 127.0.0.1] [1 bob 127.0.0.1]]
          Time:0.00018839100000000002}]}

答案 1 :(得分:2)

应将Json数组解组为Go切片或数组。您似乎正在尝试将values内的数组解组为struct

"values": [[1,"alice","127.0.0.1"], [1,"bob","127.0.0.1"]]

上面的数组数组应该被解组成Go切片。

试,

type queryResults struct {
    Results []struct {
        Columns []string `json:"columns"`
        Types   []string `json:"types"`
        Values  [][]interface{} `json:"values"`
        Time float64 `json:"time"`
    } `json:"results"`
}
Go Playground

中的

不要忽视错误。如果你试过,

err := json.Unmarshal([]byte(jsonString), &resultjson)
if(err != nil){
    fmt.Println(err)
}
你可能已经看到了这个错误。