Json(/hash) To Ruby Object?
In Javascript you can access json as objects. person = { name: { first: 'Peter', last: 'Parker' } } person.name.first In ruby I have to use it like this: person[:name
Solution 1:
You should check out the Hashie gem. It lets you do just what you are looking for. It has a Mash class which takes JSON and XML parsed hashes and gives you object-like access. It actually does deep-dives into the hash, converting any arrays or hashes inside the hash, etc.
Solution 2:
Solution 3:
JavaScript uses object attributes as its implementation of associative arrays. So, using Ruby's hash type is basically doing the same thing.
Solution 4:
Rails has built in support for encoding hashes as JSON and decoding JSON into a hash through ActiveSupport::JSON. Using built-in support avoids the need for installing a gem.
For example:
hash = ActiveSupport::JSON.decode("{ \"color\" : \"green\" }")
=> {"color"=>"green"}
hash["color"]
=> "green"
For more info, see: http://www.simonecarletti.com/blog/2010/04/inside-ruby-on-rails-serializing-ruby-objects-with-json/
Post a Comment for "Json(/hash) To Ruby Object?"