dewski / json_builder

Rails provides an excellent XML Builder by default to build RSS and ATOM feeds, but nothing to help you build complex and custom JSON data structures. JSON Builder is here to help.
http://garrettbjerkhoel.com/json_builder/
MIT License
244 stars 52 forks source link

Render hashes? #42

Open alfuken opened 11 years ago

alfuken commented 11 years ago

I have a list of prices for a product

prices = [
  #<Price currency="usd", value="130">,
  #<Price currency="eur", value="100">,
  #<Price currency="gbp", value="70">,
]

and want to render it like this:

"product": {
  "title": "foo",
  "prices": {
    "usd": 130,
    "eur": 100,
    "gbp": 70
  }
}

Problem is, array of prices is not always the same - it may or may not have other currencies, there can be 10, there can be 1, there can be none at all. I've spent whole day trying to figure out, how do I handle anything other than plain array, and couldn't find a clue. So my question is: how do I do this?

RKushnir commented 11 years ago

You can use a key method.

array prices do |price|
  key price.currency, price.value
end
alfuken commented 11 years ago

@RKushnir nah, too late, I've switched to jbuilder gem already. Not so pretty, but works great, written by rails core, and supports partials out of the box.

RKushnir commented 11 years ago

@alfuken I understand you :)