我正在嘗試解組以下由 couchDB 生成并在 Go 中返回 cURL 請求的 JSON 對象,這里沒有提到 cURL 請求代碼,因為它超出了這個問題的范圍,我已將它分配給調(diào)用的mail變量代碼部分。JSON數(shù)據(jù)結(jié)構(gòu):{"total_rows": 4,"offset": 0,"rows": [{ "id": "36587e5d091a0d49f739c25c0b000c05", "key": "36587e5d091a0d49f739c25c0b000c05", "value": { "rev": "1-92471472a3de492b8657d3103f5f6e0d" } }]}這是我對上述 JSON 對象進行解組的代碼,package mainimport ( "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 獲取該值。
2 回答

30秒到達戰(zhàn)場
TA貢獻1828條經(jīng)驗 獲得超6個贊
您定義 Rows為結(jié)構(gòu)切片,這意味著您應該使用for迭代 Rows以執(zhí)行值。
for _, item := range s.Rows {
fmt.Println(item.ID)
}
- 2 回答
- 0 關(guān)注
- 145 瀏覽
添加回答
舉報
0/150
提交
取消