How to convert JSON to a Ruby hash How to convert JSON to a Ruby hash ruby ruby

How to convert JSON to a Ruby hash


What about the following snippet?

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


You could also use Rails' with_indifferent_access method so you could access the body with either symbols or strings.

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

then

json[:val] #=> "test"json["val"] #=> "test"


Assuming you have a JSON hash hanging around somewhere, to automatically convert it into something like WarHog's version, wrap your JSON hash contents in %q{hsh} tags.

This seems to automatically add all the necessary escaped text like in WarHog's answer.