How to convert a ruby hash object to JSON?

Ruby on-RailsJsonRubyHashmap

Ruby on-Rails Problem Overview


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

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

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.

Solution 2 - Ruby on-Rails

require 'json/ext' # to use the C based extension instead of json/pure

puts {hash: 123}.to_json

Solution 3 - Ruby on-Rails

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\"}"

Solution 4 - Ruby on-Rails

Add the following line on the top of your file

require 'json'

Then you can use:

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

Alternatively, you can use:

JSON.generate({:make => "bmw", :year => "2003"})

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionkapsoView Question on Stackoverflow
Solution 1 - Ruby on-RailsMladen JablanovićView Answer on Stackoverflow
Solution 2 - Ruby on-RailsnurettinView Answer on Stackoverflow
Solution 3 - Ruby on-RailsVinicius BrasilView Answer on Stackoverflow
Solution 4 - Ruby on-RailsApurv PandeyView Answer on Stackoverflow