我想在golang中对以下数据进行json unmarshal。
{
RESPONSE : {
CODE : "123"
NEW_RESPONSE :{
0:[
{
key1:val1,
key2:val2
},
{
key3:val3,
key4:val4
}
]
1:[
{
key5:val5,
key6:val6,
key7:val7
},
{
key31:val31,
key42:val42
}
]
2:{
key8:val8,
key9:val9,
key1-:val10
}
3:{}
}
}
}
我想访问这些数据的每个键。我想做的是
type testData struct{
Code string `json:"CODE"`
NewResponse map[string]interface{} `json:"NEW_RESPONSE"`}
type GetData struct{
TestResponse testData `json:"RESPONSE"`}
之后我就不能再使用 "NewResponse "了。需要帮助。先谢谢你。
你可以访问 NewResponse
使用钥匙。
elem:=NewResponse["0"]
看着输入的文件。elem
是一个对象数组。剩下的代码将使用类型断言。
if arr, ok:=elem.([]interface{}); ok {
// arr is a JSON array
objElem:=arr[0].(map[string]interface{})
for key,value:=range objElem {
// key: "key1"
// value: "val1"
val:=value.(string)
...
}
} else if obj, ok:=elem.(map[string]interface{}); ok {
// obj is a JSON object
for key, val:=range obj {
// key: "key1"
value:=val.(string)
}
}
请验证你的json格式
这可能会解决你的目的。
package main
import (
"encoding/json"
"fmt"
)
func main() {
Json := `{
"RESPONSE" : {
"CODE" : "123",
"NEW_RESPONSE" :{
"0":{
"s" : 1,
"s1" :2,
"s3": 3
}
}
}
}`
// Declared an empty interface
var result map[string]interface{}
// Unmarshal or Decode the JSON to the interface.
err := json.Unmarshal([]byte(Json), &result)
if err != nil{
fmt.Println("Err : ",err)
}else{
fmt.Println(result)
}
}