【问题标题】:Go lang json decode mappingGo lang json 解码映射
【发布时间】:2017-07-25 09:25:53
【问题描述】:

如何将每个元素映射到结构或映射。基于不同类型的json数据。

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

我已经尝试过了。但无法按预期工作。

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

这样,我只能得到o["ret"]。我真正想要的是 o["ret"]["alias"] 或 o["ret"]["all_parents"]。

任何建议或提示都会有所帮助。谢谢。

【问题讨论】:

    标签: json dictionary go


    【解决方案1】:

    您可以使用map[string]interface{} 结果并对相关部分进行类型转换,例如:

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

    将获取数组并继续,依此类推。但是,这很乏味,您还需要检查设置的值等。

    相反,我建议您使用方便的JSON to Go tool,它可以在给定一些输入 JSON 时自动生成一个结构定义,以便您粘贴到您的 Go 代码中。

    显然,您可能需要修改它以满足您的需要,因为您知道输入可以采用哪些有效格式。不过这个工具省去了很多繁琐的样板代码编写!

    例如,对于上面的 JSON,它会生成:

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

    【讨论】:

    • JSON to Go tool 似乎是获取 json 数据结构的简单方法。感谢您的分享。
    猜你喜欢
    • 2022-01-10
    • 1970-01-01
    • 2018-05-05
    • 2023-04-04
    • 2011-05-11
    • 1970-01-01
    • 2020-06-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多