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"}'
xlembouras
  • 8,215
  • 4
  • 33
  • 42
Maddy Chavda
  • 591
  • 6
  • 10
  • 20

4 Answers4

11

Do you know about JSON.parse ?

require 'json'

my_hash = JSON.parse('{"hello": "goodbye"}')
puts my_hash["hello"] => "goodbye"
xlembouras
  • 8,215
  • 4
  • 33
  • 42
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

Amol Udage
  • 2,917
  • 19
  • 27
  • Just keep in mind, it's [eval](http://stackoverflow.com/questions/637421/is-eval-supposed-to-be-nasty) - the same can be achieved in a (IMO) more ruby way using [the answer below](http://stackoverflow.com/a/23646456/2224331) :) Happy JSON parsing :D – SidOfc Apr 13 '17 at 12:57
  • Thank you so much buddy you made my day ummmaaahhh – Adnan Jun 10 '21 at 12:32
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:

Gagan Gami
  • 10,121
  • 1
  • 29
  • 55
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
Chen Pang
  • 1,370
  • 10
  • 11
  • 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\"=>\"*/*\"}" – Maddy Chavda May 14 '14 at 05:45
  • 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' – Maddy Chavda May 14 '14 at 05:49