json 在 golang 中解组复杂的 json 数据

json unmarshal in gloang for complex json data

我想 json 在 golang 中解组以下数据:

{
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)
    }
}