我使用 CURL 将以下 JSON 数组作为 Web 服务输出接收。
{
"total_rows": 4,
"offset": 0,
"rows": [
{
"id": "_design/people",
"key": "_design/people",
"value": {
"rev": "3-d707964c8a3fa0c0c71e51c600bbafb8"
}
},
{
"id": "aamir",
"key": "aamir",
"value": {
"rev": "3-4b9095435470366fb77df1a3d466bcff"
}
},
{
"id": "iyaan",
"key": "iyaan",
"value": {
"rev": "1-4fea2c459d85480bf4841c7e581180c0"
}
},
{
"id": "tahir",
"key": "tahir",
"value": {
"rev": "2-593c9237a96836a98f53c0374902964a"
}
}
]
}
我想从中分别提取“total_rows”对象和“rows”对象。
最佳答案
你只需要包 encoding/json
。
定义行结构:
type Row struct {
Id string `json:"id"`
Key string `json:"key"`
Value struct {
Rev string `json:"rev"`
} `json:"value"`
}
定义的数据结构:
type Data struct {
TotalRows int `json:"total_rows"`
Offset int `json:"offest"`
Rows []Row `json:"rows"`
}
然后使用json.Unmarshal
:
b := []byte("json string")
data := Data{}
if err := json.Unmarshal(b, &data); err != nil {
panic(err)
}
fmt.Println(data.TotalRows, data.Offset)
for _, row := range data.Rows {
fmt.Println(row.Id, row.Key)
}
关于json - 如何在 Go 语言中读取 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44713658/