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

报告相同问题?

悬赏问题

  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化