我正在尝试将给定的 API 响应解析为结构。 好像是一个数组。
[
{
"host_name" : "hostname",
"perf_data" : "",
"plugin_output" : "All good",
"state" : 0
}
]
我不知道如何为其创建结构,我想出了:
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)
但运气不佳。
我是否应该从初始响应中删除方括号? 有人能指出我正确的方向吗?
最佳答案
您可以将 JSON 数组解码为 Go slice 。因此,解码为 []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
为此:
var servicedata []*ServiceData
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
// handle error
}
它更短、更容易阅读并且更高效。
关于arrays - 在GO中解析json对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62438871/