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?

3
  • 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. Commented Aug 29, 2010 at 7:56
  • @anurag. i wonder if there is a method that converts between json and ruby object smoothly. Commented Aug 29, 2010 at 8: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. Commented Aug 29, 2010 at 8:21

4 Answers 4

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

Sign up to request clarification or add additional context in comments.

Comments

1

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

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

Comments

0

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

1 Comment

How do I access it like an object like in Javascript?
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/

1 Comment

That's not what he was asking for.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.