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?
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"
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.
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.
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]
Success story sharing
value = '{"val":"test","val1":"test1","val2":"test2"}'
could have been more readable.