用数组解组JSON
我试图解组couchDB生成的以下JSON对象,并在Go中返回一个cURL请求,这里没有提到cURL请求代码,因为它超出了这个问题的范围,我已经在代码部分将它分配给名为用数组解组JSON,json,go,unmarshalling,Json,Go,Unmarshalling,我试图解组couchDB生成的以下JSON对象,并在Go中返回一个cURL请求,这里没有提到cURL请求代码,因为它超出了这个问题的范围,我已经在代码部分将它分配给名为mail的变量 JSON数据结构: { "total_rows": 4, "offset": 0, "rows": [{ "id": "36587e5d091a0d49f739c25c0b000c05", "key": "36587e5d091a0d49f739c25c0b0
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
,所以我尝试这样做
fmt.Printf(“%v”,s.Rows.ID)
它返回这个错误
prog.go:33:25:s.Rows.ID未定义(类型[]struct{ID string“json:\'ID\”;Key string“json:\'Key\”;Value struct{Rev string“json:\'Rev\”}json:\'Value\\”没有字段或方法ID)
但它适用于fmt.Printf(“%v”,s.Rows)
并返回
[{36587E5D091A0D49F739C25C000C05 36587E5D091A0D49F739C25C000C05{1-92471472a3de492b8657d3103f5f6e0d}}]
我的最终目标是获取36587e5d091a0d49f739c25c0b000c05
并将其分配给GO变量,但无法使用GO获取该值。您必须调用:
fmt.Println(s.Rows[0].ID)
您将行
定义为结构的切片,这意味着您应该使用迭代行来执行值
for _, item := range s.Rows {
fmt.Println(item.ID)
}