在GO中解析json对象的数组

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

我正在尝试将给定的API响应解析为一个结构。它似乎是一个数组。

[
   {
      "host_name" : "hostname",
      "perf_data" : "",
      "plugin_output" : "All good",
      "state" : 0
   }
]

我不知道如何为它创建struct,我想到了:

type ServiceData struct {
    HostName     string `json:"host_name"`
    PerfData     string `json:"perf_data"`
    PluginOutput string `json:"plugin_output"`
    State        int    `json:"state"`
}
defer resp.Body.Close()
buf := new(bytes.Buffer)
buf.ReadFrom(resp.Body)
jsonStr := buf.String()
var servicedata ServiceData
json.Unmarshal([]byte(jsonStr), &servicedata)

但是没有运气。

我也许应该从最初的答复中删除方括号?有人可以指出我正确的方向吗?

arrays json parsing go slice
1个回答
1
投票

您可以将JSON数组解组到Go切片中。因此,解组为[]ServiceData[]*ServiceData类型的值:

var servicedata []*ServiceData

正在运行的演示:

func main() {
    var result []*ServiceData
    if err := json.Unmarshal([]byte(src), &result); err != nil {
        panic(err)
    }
    fmt.Printf("%+v", result[0])
}

const src = `[
   {
      "host_name" : "hostname",
      "perf_data" : "",
      "plugin_output" : "All good",
      "state" : 0
   }
]`

哪个输出(在Go Playground上尝试):

&{HostName:hostname PerfData: PluginOutput:All good State:0}

还请注意,您可以“直接从身体上解封”,无需先阅读身体。

使用json.Decoder执行此操作:

json.Decoder

它必须更短,更容易阅读并且更有效。

© www.soinside.com 2019 - 2024. All rights reserved.