3

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][:first]

Is it possible to access json (and hash) as an object just like in javascript?

never_had_a_name
  • 90,630
  • 105
  • 267
  • 383
  • 1
    I am still learning Ruby, but to get `person.name.first` to work in Ruby, these would need to be methods. You would probably need to override the `method_missing` in Hash to do a hash lookup when the property is not found. – Anurag Aug 29 '10 at 07:56
  • @anurag. i wonder if there is a method that converts between json and ruby object smoothly. – never_had_a_name Aug 29 '10 at 08:02
  • Sure such a method can easily be written from what I understand, and most likely one would exist too. The main idea will be to dynamically add methods to the given hash instance. – Anurag Aug 29 '10 at 08:21

4 Answers4

4

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.

http://github.com/intridea/hashie

Nicholas C
  • 1,103
  • 1
  • 7
  • 14
1

There is a json gem in ruby. Perhaps that will help.

http://flori.github.com/json/

TrentEllingsen
  • 614
  • 1
  • 6
  • 17
0

JavaScript uses object attributes as its implementation of associative arrays. So, using Ruby's hash type is basically doing the same thing.

Tim McNamara
  • 18,019
  • 4
  • 52
  • 83
0

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/

Gabriel Yarra
  • 614
  • 5
  • 3