简体   繁体   English

Go Lang json解码映射

[英]Go lang json decode mapping

How can I map each element to struct or map. 如何将每个元素映射到struct或map。 Base on the json data that has different types. 基于具有不同类型的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
    }
  ]
}

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"]. 这样,我只能得到o [“ ret”]。 What I really want is o["ret"]["alias"] or o["ret"]["all_parents"]. 我真正想要的是o [“ ret”] [“ alias”]或o [“ ret”] [“ all_parents”]。

Any suggestions or tips will helps. 任何建议或提示将有所帮助。 Thanks. 谢谢。

You can use the map[string]interface{} result and typecast the relevant parts, eg: 您可以使用map[string]interface{}结果并强制转换相关部分,例如:

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. 相反,我建议您使用方便的JSON to Go工具 ,该工具可以自动生成一个结构定义,供您在输入某些JSON时粘贴到Go代码中。

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: 例如,对于上面的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"`
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM