gpt4 book ai didi

json - 用于解码 JSON 数组的 Go 结构

转载 作者:IT王子 更新时间:2023-10-29 01:40:14 26 4
gpt4 key购买 nike

所以我有一些具有 JSON 数组“pet”的 JSON(由 PetFinder API 提供)。我想从中解码,使用“encoding/json”包,一段 pet 结构。 这种结构会是什么样子?我找不到解码函数如何处理 JSON 数组的任何示例。

一旦我有了一个合适的结构,这就是我计划做的事情:

pfetch := new(PetsFetcher) // where PetsFetcher is the struct im asking for
err := json.Unmarshal(body, &pfetch)

这是正文中的 json(以一片 ascii 字节的形式):

{
"petfinder": {
"lastOffset": {
"$t": 5
},
"pets": {
"pet": [
{
"options": {
"option": [
{
"$t": "altered"
},
{
"$t": "hasShots"
},
{
"$t": "housebroken"
}
]
},
"breeds": {
"breed": {
"$t": "Dachshund"
}
}
},
{
"options": {
"option": {
"$t": "hasShots"
}
},
"breeds": {
"breed": {
"$t": "American Staffordshire Terrier"
}
},
"shelterPetId": {
"$t": "13-0164"
},
"status": {
"$t": "A"
},
"name": {
"$t": "HAUS"
}
}
]
}
}
}

提前致谢。

最佳答案

我真的不知道那些 $t 属性在你的 JSON 中做了什么,所以让我们用一个简单的例子来回答你的问题。要解码此 JSON:

{
"name": "something",
"options": [
{
"key": "a",
"value": "b"
},
{
"key": "c",
"value": "d"
},
{
"key": "e",
"value": "f"
},
]
}

您需要在 Go 中输入此 Data:

type Option struct {
Key string
Value string
}

type Data struct {
Name string
Options []Option
}

关于json - 用于解码 JSON 数组的 Go 结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17129767/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com