Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a ruby hash object to JSON?

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 RubyDoc and obviously Hash object doesn't have a to_json method. But I am reading on blogs that Rails supports active_record.to_json and also supports hash#to_json. I can understand ActiveRecord is a Rails object, but Hash is not native to Rails, it's 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 
like image 978
kapso Avatar asked Jul 06 '10 05:07

kapso


People also ask

How do you turn JSON into a Ruby object?

The most simplest way to convert a json into a Ruby object is using JSON. parse and OpenStruct class. If there are more subsequence keys after the response , the object. response will returns another instance of the OpenStruct class holding the subsequence methods as those subsequence keys.

What does JSON dump do in Ruby?

Dumps obj as a JSON string, i.e. calls generate on the object and returns the result. If anIO (an IO-like object or an object that responds to the write method) was given, the resulting JSON is written to it. If the number of nested arrays or objects exceeds limit, an ArgumentError exception is raised.


2 Answers

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.

like image 145
Mladen Jablanović Avatar answered Sep 21 '22 15:09

Mladen Jablanović


require 'json/ext' # to use the C based extension instead of json/pure  puts {hash: 123}.to_json 
like image 20
nurettin Avatar answered Sep 22 '22 15:09

nurettin