[英]Retrieve unknow key names and values from a JSON array list
[
{"id_A": 1, "name_A": "Value_A"},
{"id_B": 2, "name_B": "Value_B"}
]
"id_ " and "name_ " can change and I need to recover both the keys names to create a struct. “id_ ”和“name_ ”可以改变,我需要恢复这两个键名来创建一个结构。
how can i do?我能怎么做?
https://play.golang.org/p/OXqpudiWWcH https://play.golang.org/p/OXqpudiWWcH
if you have the key which is not fix, the only way you can use is interface{} you need to unmarshal json to []interface{}
and using type assertion to map[string]interface{}
如果您有未修复的密钥,您可以使用的唯一方法是 interface{} 您需要将 json 解组为
[]interface{}
并使用类型断言map[string]interface{}
var body []interface{}
_ = json.Unmarshal([]byte(json2), &body)
fmt.Printf("Unmarshaled: %v\n", body)
// range through array interface[]
for _, opt := range body {
// assert interface{} to map[string]interface{}
if item, ok := opt.(map[string]interface{}); ok {
for v, opt := range item {
fmt.Printf("[%s] key -> %s value -> %s\n", v, opt, "fake")
}
}
}
the complete code based on your example https://play.golang.org/p/PepxOVlB7u4基于您的示例的完整代码https://play.golang.org/p/PepxOVlB7u4
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.