简体   繁体   中英

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

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

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

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

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

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

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM