How to convert ruby formatted json string to json hash in ruby?
Solution 1
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
Solution 2
Do you know about JSON.parse ?
require 'json'
my_hash = JSON.parse('{"hello": "goodbye"}')
puts my_hash["hello"] => "goodbye"
Solution 3
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:
Solution 4
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
Maddy Chavda
No one is useless in this world who lightens the burdens of another.
Updated on July 31, 2022Comments
-
Maddy Chavda over 1 year
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"}'