Reputation: 591
I want to access json string like hash object so that i can access json using key value like temp["anykey"]
. How to convert ruby formatted json string into json object?
I have following json string
temp = '{"accept"=>"*/*", "host"=>"localhost:4567", "version"=>"HTTP/1.1",
"user_agent"=>"curl/7.22.0 (x86_64-pc-linux-gnu) libcurl/7.22.0 OpenSSL/1.0.1 zlib/1.2.3.4 libidn/1.23 librtmp/2.3",
"http_token"=>"375fe428b1d32787864264b830c54b97"}'
Upvotes: 5
Views: 19368
Reputation: 3075
You can try eval method on temp json string
Example:
eval(temp)
This will return following hash
{"accept"=>"*/*", "host"=>"localhost:4567", "version"=>"HTTP/1.1", "user_agent"=>"curl/7.22.0 (x86_64-pc-linux-gnu) libcurl/7.22.0 OpenSSL/1.0.1 zlib/1.2.3.4 libidn/1.23 librtmp/2.3", "http_token"=>"375fe428b1d32787864264b830c54b97"}
Hope this will help.
Thanks
Upvotes: 7
Reputation: 10251
if your parse this string to ruby object, it will return a ruby Hash object, you can get it like this You can install the json gem for Ruby
gem install json
You would require the gem in your code like this:
require 'rubygems'
require 'json'
Then you can parse your JSON string like this:
ruby_obj = JSON.parse(json_string)
There are also other implementations of JSON for Ruby:
Upvotes: 5
Reputation: 1388
To convert a Ruby hash to json string, simply call to_json.
require 'json'
temp = {"accept"=>"*/*", "host"=>"localhost:4567", "version"=>"HTTP/1.1",
"user_agent"=>"curl/7.22.0 (x86_64-pc-linux-gnu) libcurl/7.22.0 OpenSSL/1.0.1 zlib/1.2.3.4 libidn/1.23 librtmp/2.3",
"http_token"=>"375fe428b1d32787864264b830c54b97"}
temp.to_json
Upvotes: 1
Reputation: 8295
Do you know about JSON.parse ?
require 'json'
my_hash = JSON.parse('{"hello": "goodbye"}')
puts my_hash["hello"] => "goodbye"
Upvotes: 11