Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

golang struct for json with arbitrary keys [duplicate]

Tags:

json

go

I am trying to write a struct type that can handle a json response like this

{"items":
[{"name": "thing",
  "image_urls": {
    "50x100": [{
      "url": "http://site.com/images/1/50x100.jpg",
      "width": 50,
      "height": 100
    }, {
      "url": "http://site.com/images/2/50x100.jpg",
      "width": 50,
      "height": 100
    }],
    "200x300": [{
      "url": "http://site.com/images/1/200x300.jpg",
      "width": 200,
      "height": 300
    }],
    "400x520": [{
      "url": "http://site.com/images/1/400x520.jpg",
      "width": 400,
      "height": 520
    }]
  }
}

Since the keys are not the same every time... a different response may have more or less keys, different ones, and as you can see with the 50x100 return multiple images for a particular size how can I create a struct that matches this?

I can do like:

type ImageURL struct {
    Url string
    Width, Height int
}

for an individual item, and a list of them for a particular key. But how does the containing struct look?

Something like:

type Images struct {
    50x100 []ImageURL
    ...
}
type Items struct {
    name string
    Image_Urls []Images
}

Might work, but I can't enumerate all of the possible image size responses. Also that Image_Urls at the end there isn't truly a list. I'd like to be able to dump it right into json.Unmarshal if possible.

like image 458
MichaelB Avatar asked Apr 04 '13 17:04

MichaelB


1 Answers

Your json looks more like a map to me.

type Items map[string][]ImageUrl

should do what you want.

like image 126
Jeremy Wall Avatar answered Sep 28 '22 04:09

Jeremy Wall