Convert json to 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 Ruby hash?

Answers


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 ruby's method: with_indifferent_access 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


Have you tried: http://flori.github.com/json/.

Failing that, you could just parse it out? If it's only arrays you're interested in, something to split the above out will be quite simple. N


You can use the nice_hash gem: https://github.com/MarioRuiz/nice_hash

require 'nice_hash'
my_string = '{"val":"test","val1":"test1","val2":"test2"}'

# on my_hash will have the json as a hash, even when nested with arrays
my_hash = my_string.json

# you can filter and get what you want even when nested with arrays
vals = my_string.json(:val1, :val2)

# even you can access the keys like this:
puts my_hash._val1
puts my_hash.val1
puts my_hash[:val1]

Need Your Help

MySQL: View with Subquery in the FROM Clause Limitation

mysql sql view mysql-error-1349

In MySQL 5.0 why does the following error occur when trying to create a view with a subquery in the FROM clause?

Model Containing List of Models (MVC-3, Razor)

model asp.net-mvc-3 razor

This problem has been plaguing me for two days now. There are some similar posts, but none that address my problem completely.