解组JSON与元件2层深

时间:2019-02-01 12:56:14

标签: json go

如何提取JSON结构的子节?

我正在解析一个API调用,该调用以以下方式返回数据(为简洁起见进行了修剪):

{
    "report": [
        {
            "item1": [
                {"name":"somename", "someint":"1", "somefloat":"2.0"}
            ]
        }
    ]
}

所以在python中,我会这样做:

data = json.loads(myvar)['report'][0]['item1'][0] print data['name']

在Go中如何完成?我不能改变或调整上游API。

type MyData struct {
    name string
    someint int
    somefloat float
}

var x MyData

// If I print APICall.buff.Bytes() here I see the valid JSON object I want to parse.

if err := json.Unmarshal(APICall.buff.Bytes(), &MyData); err != nil {
    log.Fatal(err)
}

fmt.Printf("%+v\n", MyData)

这成功运行,但是我的结构中充满了空键。

&{name: someint:0 somefloat:0}

1 个答案:

答案 0 :(得分:3)

您可以使用地图类型

var x map[string]interface{} // Adapt to match with the JSON structure

或者您可以详细说明JSON的所有结构

type Item struct {
   Name string `json:"name,omitempty"`
   Someint int `json:"Someint,omitempty"` // or string depend on the data type
   Somefloat float32 `json:"somefloat,omitempty"` // or string depend on the data type
}

type Report struct {
   Report     []map[string][]Item  `json:"report,omitempty"` // map[string] because it item1 so I assume it can be item2, item3...
}

更正您所需的代码:

package main

import (
    "fmt"
    "encoding/json"
)

func main() {
   type Item struct {
     Name string `json:"name,omitempty"`
     Someint string `json:"Someint,omitempty"` // or int depend on the data type
     Somefloat string `json:"somefloat,omitempty"` // or float32 depend on the data type
   }

   type Report struct {
      Report     []map[string][]Item  `json:"report,omitempty"` // map[string] because it item1 so I assume it can be item2, item3...
   }

   var x Report

   // If I print APICall.buff.Bytes() here I see the valid JSON object I want to parse.

   if err := json.Unmarshal([]byte(`{
    "report": [
        {
            "item1": [
                {"name":"somename1", "someint":"1", "somefloat":"2.0"},
                {"name":"somename2", "someint":"2", "somefloat":"3.0"}
            ],
            "item2": [
                {"name":"somename1", "someint":"1", "somefloat":"2.0"},
                {"name":"somename2", "someint":"2", "somefloat":"3.0"}
            ]
        }
    ]
   }`), &x); err != nil {
      fmt.Println(err)
   }

   fmt.Printf("%+v\n%+v", x, x.Report[0]["item1"][0])
}

输出:

{Report:[map[item1:[{Name:somename1 Someint:1 Somefloat:2.0} {Name:somename2 Someint:2 Somefloat:3.0}] item2:[{Name:somename1 Someint:1 Somefloat:2.0} {Name:somename2 Someint:2 Somefloat:3.0}]]]}

{Name:somename1 Someint:1 Somefloat:2.0}