英文:
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"`
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论