How to convert JSON to a Ruby hash

verdure picture verdure · Nov 1, 2011 · Viewed 140.6k times · Source

I have a JSON object holding the following value:

@value = {"val":"test","val1":"test1","val2":"test2"}

I want to loop through it in Ruby to get the key/value pairs. When I use @each, it doesn't iterate through the object because it is not in the Ruby hash form:

@value = {"val"=>"test","val1"=>"test1","val2"=>"test2"}

How can I convert the above JSON object to a Ruby hash?

Answer

WarHog picture WarHog · Nov 1, 2011

What about the following snippet?

require 'json'
value = '{"val":"test","val1":"test1","val2":"test2"}'
puts JSON.parse(value) # => {"val"=>"test","val1"=>"test1","val2"=>"test2"}