Golang 中的 Json 解码/解码

标签 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}]}

最佳答案

Json 数组应该解码为 Go slice 或数组。看起来您正在尝试将 values 中的数组解码为 struct

“值”:[[1,"alice","127.0.0.1"], [1,"bob","127.0.0.1"]]

上面的数组数组应该被解码成 Go slice 的 slice 。

尝试,

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)
}

您可能已经看到了错误。

关于Golang 中的 Json 解码/解码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36467158/

相关文章:

javascript - 无法通过 jQuery 获取要显示的 JSON 属性

go - 打印/访问超出范围的 slice 索引时不要 panic

testing - 如何在 Golang 中测试日志记录(log.Println)?

json - 为什么编码(marshal)无法使用嵌套结构?

java - Jackson - 使用注释将第一个数组成员绑定(bind)到对象

java - 获取 java.rmi.UnmarshalException : unrecognized method hash: method not supported by remote object

json - JSONObject 的 Jackson 2 等价物是什么?

java - 无法反序列化 `java.time.Instant` 类型的值 - Jackson

python - 如何访问字典列表中的值?

tcp - Google Go EOF 使用 Read() 从连接读取