How to convert a ruby hash object to JSON? How to convert a ruby hash object to JSON? ruby ruby

How to convert a ruby hash object to JSON?


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'# => truecar.to_json# => "{"make":"bmw","year":"2003"}"

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


require 'json/ext' # to use the C based extension instead of json/pureputs {hash: 123}.to_json


You can also use JSON.generate:

require 'json'JSON.generate({ foo: "bar" })=> "{\"foo\":\"bar\"}"

Or its alias, JSON.unparse:

require 'json'JSON.unparse({ foo: "bar" })=> "{\"foo\":\"bar\"}"