为了账号安全,请及时绑定邮箱和手机立即绑定

如何从 API 获取 JSON 并计算鸽子数量

如何从 API 获取 JSON 并计算鸽子数量

Go
胡子哥哥 2023-08-21 14:48:10
所以我试图从具有这种格式的 JSON 中获取鸽子的数量。该 JSON 包含许多鸟类类型,每种鸟类都由其颜色和最后一次接触来定义:{    "url": "http://localhost:9001/",    "pigeons": [        {            "color": "white",            "lastContact": "2020-03-23T14:46:20.806Z"        },        {            "color": "grey",            "lastContact": "2020-03-23T14:46:20.807Z"        }    ],    "parrots": [        {            "color": "green",            "lastContact": "2020-03-23T14:46:20.806Z"        }    ]}已经编写了这段从 API 获取 JSON 的代码,但是由于我没有任何 Go 经验,你们能帮我计算这里的鸽子数量吗?我并不关心其他鸟类的数量。package mainimport (    "encoding/json"    "fmt"    "io/ioutil"    "log"    "net/http"    "time")type pigeons struct {    Number int `json:"something"`}func main() {    url := "http://localhost:9001"    birdsClient := http.Client{        Timeout: time.Second * 2, // Maximum of 2 secs    }    req, err := http.NewRequest(http.MethodGet, url, nil)    if err != nil {        log.Fatal(err)    }    res, getErr := birdsClient.Do(req)    if getErr != nil {        log.Fatal(getErr)    }    body, readErr := ioutil.ReadAll(res.Body)    if readErr != nil {        log.Fatal(readErr)    }    pigeons1 := pigeons{}    jsonErr := json.Unmarshal(body, &pigeons1)    if jsonErr != nil {        log.Fatal(jsonErr)    }    fmt.Println(pigeons1.Number)}
查看完整描述

1 回答

?
繁星淼淼

TA贡献1775条经验 获得超11个赞

返回的 JSON 文档中,pigeons有一个数组,看起来该数组的长度就是鸽子的数量。因此,如果您将其解组到一个接受鸽子数组的结构体中,您可以获得它的长度:

type pigeons struct {
   Pigeons []interface{} `json:"pigeons"`
   }

在上面,您可以将pigeons字段解组到接口数组,因为您不关心字段的内容。如果需要处理内容,则需要一个单独的结构并使用该结构的数组。然后:

var p pigeons
json.Unmarshal(body, &p)
fmt.Printf("%d",len(p.Pigeons))


查看完整回答
反对 回复 2023-08-21
  • 1 回答
  • 0 关注
  • 76 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信