Go structure for unmarshalling a JSON array

7,152 views
Skip to first unread message

turn...@gmail.com

unread,
Jun 15, 2013, 10:58:40 PM6/15/13
to golan...@googlegroups.com

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.

Message has been deleted
Message has been deleted

Peter Nguyen

unread,
Jun 16, 2013, 3:47:35 AM6/16/13
to golan...@googlegroups.com
I recently wondered the same thing and finally found out how it can be done. One solution is to define struct types that match your JSON structure, so in your case it will be something like:


type PetFinder struct {
    Pets struct {
        pet []Pet
    }
}


type Pet struct {
    Options struct {
        Option map[string]string
    }
    Breeds struct {
       Breed map[string]string
    }
}

pfetch := &PetFinder{} // where PetsFetcher is the struct im asking for
err := json.Unmarshal(body, &pfetch)
fmt.Println(pfetch.Pets)

One advantage of having the struct types is that the fields that you don't declare in your struct types will be ignored, which should help on memory usage if you can't control the JSON structure that you're getting from the API.


Another way is to use the interface{} type, but this will require you to iterate through the whole variable to get what you want.

var pfetch interface{} // where PetsFetcher is the struct im asking for
err := json.Unmarshal(body, &pfetch)
fmt.Println(pfetch)


You can read more about it here http://blog.golang.org/json-and-go

Nguyên Nguyễn Văn Cao

unread,
Jun 16, 2013, 5:02:14 AM6/16/13
to golan...@googlegroups.com
Just do at Pater Nguyen said.
Here is a package that help you alot for this: https://github.com/bashtian/jsonutils , feed it with  a JSON string, and it will return for you a block of Go code.(thought it still need some improment).

Vào 09:58:40 UTC+7 Chủ nhật, ngày 16 tháng sáu năm 2013, Devin Turner đã viết:

Devin Turner

unread,
Jun 16, 2013, 6:54:50 AM6/16/13
to golan...@googlegroups.com
Thanks for the help.  I also stumbled on this library and it was pretty easy to use https://github.com/bitly/go-simplejson

Shivakumar GN

unread,
Jun 16, 2013, 1:33:41 PM6/16/13
to golang-nuts


--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.
 
 

John Nagle

unread,
Jun 17, 2013, 3:07:30 AM6/17/13
to golan...@googlegroups.com
On 6/16/2013 10:33 AM, Shivakumar GN wrote:
> This post on G+.might be of interest
> https://plus.google.com/u/0/118258700474648954770/posts/Pz7trH5W5p6?cfem=1
>
> On Sun, Jun 16, 2013 at 4:24 PM, Devin Turner <turn...@gmail.com> wrote:
>
>> Thanks for the help. I also stumbled on this library and it was pretty
>> easy to use https://github.com/bitly/go-simplejson

This seems to turn JSON into a tree of "[]interface{}" items, for
which some down-conversion functions are provided. Arrays of
"[]interface{}" seem to come up frequently in Go. SQL query results,
for example, come back that way. There should be more standard
tools for dealing with this type.

A good way to convert structs to arrays of "[]interface{}" and
back would be useful. That can be done with reflection, but it's
slow. It can also be done by external code generators, like
the one for Google protocol buffers. That's efficient at
run time, but clunky at build time.

>> On Sunday, June 16, 2013 4:02:14 AM UTC-5, Nguyên Nguyễn Văn Cao wrote:
>>>
>>> Just do at Pater Nguyen said.
>>> Here is a package that help you alot for this: https://github.com/**
>>> bashtian/jsonutils <https://github.com/bashtian/jsonutils> , feed it
>>> with a JSON string, and it will return for you a block of Go code.(thought
>>> it still need some improvement).

That's more for constants. You put in JSON, and then get code which
must be compiled.

John Nagle

Reply all
Reply to author
Forward
0 new messages