5

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"}'
1
  • What you have in the post is not a valid JSON, it looks more like a Hash.to_s result Commented May 14, 2014 at 6:48

4 Answers 4

11

Do you know about JSON.parse ?

require 'json'

my_hash = JSON.parse('{"hello": "goodbye"}')
puts my_hash["hello"] => "goodbye"
Sign up to request clarification or add additional context in comments.

Comments

7

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

1 Comment

Just keep in mind, it's eval - the same can be achieved in a (IMO) more ruby way using the answer below :) Happy JSON parsing :D
5

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:

Comments

1

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

2 Comments

i did that temp.to_json gives me "{\"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\", \"host\"=>\"localhost:4567\", \"version\"=>\"HTTP/1.1\", \"http_token\"=>\"375fe428b1d32787864264b830c54b97\", \"accept\"=>\"*/*\"}"
i stored it in t1 and then access like t1['version']. it doesn't give me value of key 'version' but it gives me key itself 'version'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.