json - 使用数组解组 JSON
问题描述
我正在尝试解组以下由 couchDB 生成并在 Go 中为 cURL 请求返回的 JSON 对象,此处未提及 cURL 请求代码,因为它超出了此问题的范围,我已将其分配给调用的mail
变量代码部分。
JSON数据结构:
{
"total_rows": 4,
"offset": 0,
"rows": [{
"id": "36587e5d091a0d49f739c25c0b000c05",
"key": "36587e5d091a0d49f739c25c0b000c05",
"value": {
"rev": "1-92471472a3de492b8657d3103f5f6e0d"
}
}]
}
这是我解组上述 JSON 对象的代码,
package main
import (
"fmt"
"encoding/json"
)
type Couchdb struct {
TotalRows int `json:"total_rows"`
Offset int `json:"offset"`
Rows []struct {
ID string `json:"id"`
Key string `json:"key"`
Value struct {
Rev string `json:"rev"`
} `json:"value"`
} `json:"rows"`
}
func main() {
mail := []byte(`{"total_rows":4,"offset":0,"rows":[{"id":"36587e5d091a0d49f739c25c0b000c05","key":"36587e5d091a0d49f739c25c0b000c05","value":{"rev":"1-92471472a3de492b8657d3103f5f6e0d"}}]}`)
var s Couchdb
err := json.Unmarshal(mail, &s)
if err != nil {
panic(err)
}
//fmt.Printf("%v", s.TotalRows)
fmt.Printf("%v", s.Rows)
}
并且上面的代码工作正常,您可以在 Go Play Ground 中通过此链接访问工作代码。
我需要获得的36587e5d091a0d49f739c25c0b000c05
价值,id
所以rows
我试图这样做
fmt.Printf("%v", s.Rows.ID)
它返回此错误
prog.go:33:25: s.Rows.ID undefined (type []struct { ID string "json:\"id\""; Key string "json:\"key\""; Value struct { Rev string "json:\"rev\"" } "json:\"value\"" } has no field or method ID)
但它适用fmt.Printf("%v", s.Rows)
并返回
[{36587e5d091a0d49f739c25c0b000c05 36587e5d091a0d49f739c25c0b000c05 {1-92471472a3de492b8657d3103f5f6e0d}}]
我的最终目标是获取36587e5d091a0d49f739c25c0b000c05
并将其分配给 GO 变量,但坚持使用 GO 获取该值。
解决方案
你必须打电话:
fmt.Println(s.Rows[0].ID)
推荐阅读
- sql - 数据未显示在表格中,仅显示列名
- swiftui - 如何避免在状态变量更新上呈现非相关视图
- python - 网页抓取大量链接?
- java - 带有 CustomAdapter 的片段中的多个 OnClickListener
- c++ - 指向地图内对象的指针无效,但该对象仍然存在(可执行代码示例)
- python - Keras model.evaluate_generator 不打印预期损失(和准确性?)
- php - 如何在 laravel 中优化数据库中的多值查询
- javascript - jQuery轮播自动播放动画
- c# - 在 ASP.NET MVC 中从视图到控制器获取文本框值时遇到问题
- cocoapods - pod 安装错误:curl:(18)传输已关闭,剩余 54357829 字节可读取