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"`
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Centos7 / PETGEM
  • ¥15 csmar数据进行spss描述性统计分析
  • ¥15 各位请问平行检验趋势图这样要怎么调整?说标准差差异太大了
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 wpf界面一直接收PLC给过来的信号,导致UI界面操作起来会卡顿
  • ¥15 init i2c:2 freq:100000[MAIXPY]: find ov2640[MAIXPY]: find ov sensor是main文件哪里有问题吗
  • ¥15 运动想象脑电信号数据集.vhdr
  • ¥15 三因素重复测量数据R语句编写,不存在交互作用
  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗