首页 > 解决方案 > 使用数组解组 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 获取该值。

标签: jsongounmarshalling

解决方案


你必须打电话:

fmt.Println(s.Rows[0].ID)

推荐阅读