在gloang中对复杂的json数据进行json unmarshal。

问题描述 投票:0回答:1

我想在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 "了。需要帮助。先谢谢你。

json go unmarshalling
1个回答
1
投票

你可以访问 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)
   }
}

0
投票

请验证你的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)
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.