Go语言JSON解码映射

huangapple go评论164阅读模式
英文:

Go lang json decode mapping

问题

如何将每个元素映射到结构体或映射?根据具有不同类型的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"]

有什么建议或提示吗?谢谢。

英文:

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

得分: 2

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

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

将获取数组并继续进行操作。然而,这种方法很繁琐,你还需要检查设置的值等。

相反,我建议你使用方便的JSON to Go工具,它可以在给定一些输入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"`
}
英文:

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

huangapple
  • 本文由 发表于 2017年7月25日 17:25:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/45299133.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定