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
This question is related to
ruby-on-rails
json
ruby
hashmap
require 'json/ext' # to use the C based extension instead of json/pure
puts {hash: 123}.to_json
You should include json
in your file
For Example,
require 'json'
your_hash = {one: "1", two: "2"}
your_hash.to_json
For more knowledge about json
you can visit below link.
Json Learning
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\"}"
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"})
Source: Stackoverflow.com