Go结构用于解组JSON数组

时间:2013-06-16 02:56:37

标签: json go

所以我有一些JSON(由PetFinder API提供),它有一个JSON数组“pet”。我希望从中解组,使用“encoding / json”包,一片宠物结构。 这种结构会是什么样的?我找不到任何关于unmarshall函数如何处理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"
          }
        }
      ]
    }
  }
}

提前致谢。

2 个答案:

答案 0 :(得分:2)

我真的不知道那些$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
}

答案 1 :(得分:1)

您可以将javascript数组解组为切片。 marhsal / unmarshalling规则在json package中的Marshal下描述。

要解组看起来像“$ t”的键,您必须注释它将解压缩到的结构。

例如:

type Option struct {
    Property string `json:"$t,omitempty"`
}

可能是出现的$ t是一个错误,应该是字典中的键。