dousui8263 2016-04-07 05:09
浏览 41
已采纳

Json在Golang中解码/解组

I have the following 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}]}

where values can have any number of elements [] inside them. When i try to unmarshal the json into a struct, the "values" tag does not get parsed properly

struct:

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"`
    }

Code:

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

Current Output:

{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}]}

Expected Output:

{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条回答 默认 最新

  • duangua5308 2016-04-07 05:37
    关注

    Json arrays should be unmarshalled into Go slices or arrays. Looks like you are trying to unmarshal the arrays inside values to a struct

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

    Above array of arrays should be unmarshalled into a Go slice of slices.

    try,

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

    in Go Playground

    And don't ignore errors. If you tried,

    err := json.Unmarshal([]byte(jsonString), &resultjson)
    if(err != nil){
        fmt.Println(err)
    }
    

    you could have seen the error.

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

报告相同问题?

悬赏问题

  • ¥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 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?