我正在尝试在 GO 上解析嵌套的 json,
json 看起来像这样:
{
"id" : 12345656,
"date" : "2018-05-02-18-16-17",
"lists" : [
{
"empoyee_id": "12343",
"name": "User1"
},
{
"contractor_id" : "12343",
"name": "User1"
},
{
"contractor_id" : "12343",
"name": "User1"
}
]
}
我的结构
type Result struct {
id int64 `json:"id"`
Date string `json:"date"`
Lists []string `json:"lists"`
}
我正在尝试使用以下方式访问它:
var result Result
json.Unmarshal(contents, &result)
如何更改以上内容以访问 employee_id 或 contractor_id 字段?
最佳答案
您需要使用另一种类型来存储嵌套数据而不是像这样的字符串片段:
package main
import (
"fmt"
"encoding/json"
)
var contents string = `{
"id" : 12345656,
"date" : "2018-05-02-18-16-17",
"lists" : [
{
"empoyee_id": "12343",
"name": "User1"
},
{
"contractor_id" : "12343",
"name": "User1"
},
{
"contractor_id" : "12343",
"name": "User1"
}
]
}`
type Result struct {
ID int64 `json:"id"`
Date string `json:"date"`
Lists []Contractor `json:"lists"`
}
type Contractor struct {
ContractorID string `json:"contractor_id"`
EmployeeID string `json:"employee_id"`
Name string `json:"name"`
}
func main() {
var result Result
err := json.Unmarshal([]byte(contents), &result)
if err != nil {
panic(err)
}
fmt.Println(result)
}
可执行文件:
https://play.golang.org/p/7dYArgz1V8y
如果您只想在嵌套对象上使用单个 ID 字段,则需要对结果执行自定义解码函数以确定存在的 ID。
关于go - 使用 go 解析嵌套的 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50203310/