rubyjsonhashmap

How to convert JSON to a Ruby hash


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?


Solution

  • require 'json'
    value = '{"key_1":"value_1", "key_2":"value_2"}'
    puts JSON.parse(value) # => {"key_1"=>"value_1","key_2"=>"value_2"}