用于解组JSON数组的Go结构

So I have some JSON (courtesy of the PetFinder API) that has a JSON array "pet". I want to unmarshal from it, using the "encoding/json" package, a slice of pet structs. What would this kind of structure look like? I can't find any examples of how the unmarshall function handles JSON arrays.

Here's what I was planning to do once I had a proper struct:

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

And here's the json that is in body (in the form of a slice of ascii bytes):

{
  "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"
          }
        }
      ]
    }
  }
}

Thanks in advance.

I really have no idea what those $t attributes are doing there in your JSON, so let’s answer your question with a simple example. To unmarshal this JSON:

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

You need this Data type in Go:

type Option struct {
    Key   string
    Value string
}

type Data struct {
    Name    string
    Options []Option
}

You can unmarshal a javascript array into a slice. The marhsal/unmarshalling rules are described under Marshal in the json package.

To unmarshal keys that look like "$t", you'll have to annotate the struct that it'll unpack into.

For example:

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

It may be that the $t that appear are a mistake, and are supposed to be keys in a dictionary.