verdure
verdure

Reputation: 3341

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?

Upvotes: 161

Views: 192047

Answers (5)

Mario Ruiz
Mario Ruiz

Reputation: 72

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]

Upvotes: 0

the Tin Man
the Tin Man

Reputation: 160551

I'm surprised nobody pointed out JSON's [] method, which makes it very easy and transparent to decode and encode from/to JSON.

If object is string-like, parse the string and return the parsed result as a Ruby data structure. Otherwise generate a JSON text from the Ruby data structure object and return it.

Consider this:

require 'json'

hash = {"val":"test","val1":"test1","val2":"test2"} # => {:val=>"test", :val1=>"test1", :val2=>"test2"}
str = JSON[hash] # => "{\"val\":\"test\",\"val1\":\"test1\",\"val2\":\"test2\"}"

str now contains the JSON encoded hash.

It's easy to reverse it using:

JSON[str] # => {"val"=>"test", "val1"=>"test1", "val2"=>"test2"}

Custom objects need to_s defined for the class, and inside it convert the object to a Hash then use to_json on it.

Upvotes: 8

WarHog
WarHog

Reputation: 8710

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

Upvotes: 296

boulder_ruby
boulder_ruby

Reputation: 39695

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.

Upvotes: 5

crims345
crims345

Reputation: 698

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"

Upvotes: 57

Related Questions