douquan2023 2017-07-25 09:25
浏览 33
已采纳

Go Lang json解码映射

How can I map each element to struct or map. Base on the json data that has different types.

{
  profile: {
    execution_time: 34,
    server_name: "myServer.net"
  },
  result: "ok",
  ret: [
    {
      alias: "asda444444",
      all_parents: [
        123,
        2433369,
        243628,
        2432267,
        62
      ],
      bankrupt: false,
      block: false,
      card: null
    }
  ]
}

I had tried this already. But not work as expected.

var o map[string]interface{}
err := json.Unmarshal(data, &o)
if err != nil {
        revel.INFO.Println("Json Decode Error", err)
    }
fmt.Println(o)

By this way, I can only get o["ret"]. What I really want is o["ret"]["alias"] or o["ret"]["all_parents"].

Any suggestions or tips will helps. Thanks.

  • 写回答

1条回答 默认 最新

  • dpbv85276 2017-07-25 09:33
    关注

    You can use the map[string]interface{} result and typecast the relevant parts, e.g.:

    o["ret"].([]interface{})
    

    would get the array and continue so on. However, this is tedious and you need to check for values being set etc as well.

    Instead, I'd recommend you use the handy JSON to Go tool that can automatically generate a struct definition for you to paste into your Go code when given some input JSON.

    Obviously you might need to amend this to suit your needs as you know what valid formats the input can take. However, this tool saves a lot of tedious boilerplate code writing!

    For example, for the JSON above, it generates:

    type AutoGenerated struct {
        Profile struct {
            ExecutionTime int `json:"execution_time"`
            ServerName string `json:"server_name"`
        } `json:"profile"`
        Result string `json:"result"`
        Ret []struct {
            Alias string `json:"alias"`
            AllParents []int `json:"all_parents"`
            Bankrupt bool `json:"bankrupt"`
            Block bool `json:"block"`
            Card interface{} `json:"card"`
        } `json:"ret"`
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊
  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写
  • ¥20 Qcustomplot缩小曲线形状问题
  • ¥15 企业资源规划ERP沙盘模拟
  • ¥15 树莓派控制机械臂传输命令报错,显示摄像头不存在
  • ¥15 前端echarts坐标轴问题