tags:

views:

290

answers:

1

How to convert a ruby hash object to JSON? So I am trying this example below & it doesn't work?

I was looking at the RubDoc and obviously Hash object doesn't have a to_json method. But I am reading blogs, that Rails supports active_record.to_json and it also supports hash#to_json. I can understand ActiveRecord is a Rails object, but Hash is not native to Rails, its a pure Ruby object. So in rails you can do a hash.to_json, but not in pure ruby??

car = {:make => "bmw", :year => "2003"}
car.to_json
+5  A: 

One of the numerous niceties of Ruby is the possibility to extend existing classes with your own methods. That's called "class reopening" or monkey-patching (the meaning of the latter can vary, though).

So, take a look here:

car = {:make => "bmw", :year => "2003"}
# => {:make=>"bmw", :year=>"2003"}
car.to_json
# NoMethodError: undefined method `to_json' for {:make=>"bmw", :year=>"2003"}:Hash
#   from (irb):11
#   from /usr/bin/irb:12:in `<main>'
require 'json'
# => true
car.to_json
# => "{"make":"bmw","year":"2003"}"

As you can see, requiring json has magically brought method to_json to our Hash.

Mladen Jablanović
all i can say is wow :) also thanks a lot!!so basically i was able to extend the json class dynamically??
I tried the same thing with Ruby object and it does not work??>> require 'json'=> true>> class Person>> attr_accessor :fname, :lname>> end=> nil>> p = Person.new=> #<Person:0x101155f70>>> p.fname = "Bill"=> "Bill">> p.lname = "Shine"=> "Shine">> p.to_json=> "\"#<Person:0x101155f70>\""
No, no, someone has to code how the object of an arbitrary class should be serialized to JSON. They did it for `Hash` and `Array` classes in `json` gem, but your class `Person` is just a plain `Object`. But you can inherit `Hash` instead. You can open a new question if you don't manage.
Mladen Jablanović
thanks. here's the new question, any help would be appreciated. Thanks.http://stackoverflow.com/questions/3226054/how-to-convert-a-ruby-object-to-json