开发者

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[开发者_StackOverflow社区: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/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜