user2377245
user2377245

Reputation: 37

Convert JSON to string or hash in ruby

I have tried:

require 'net/http'
require 'json'
require 'pp'
require 'uri'

url = "http://xyz.com"
resp = Net::HTTP.get_response(URI.parse(url))
buffer = resp.body
result = JSON.parse(buffer)
#result.to_hash
    #pp result
puts result  

And got the output as:

{"id"=>"ABC", "account_id"=>"123", "first_name"=> "PEUS" }

in JSON format but I only need the value of id to be printed as ABC.

Upvotes: 2

Views: 16160

Answers (1)

the Tin Man
the Tin Man

Reputation: 160621

Your incoming string in JSON would look like:

{"id":"ABC","account_id":"123","first_name":"PEUS"}

After parsing with JSON it's the hash:

{"id"=>"ABC", "account_id"=>"123", "first_name"=> "PEUS" }

So, I'd use:

hash = {"id"=>"ABC", "account_id"=>"123", "first_name"=> "PEUS" }
hash['id'] # => "ABC"

Here's a more compact version:

require 'json'

json = '{"id":"ABC","account_id":"123","first_name":"PEUS"}'
hash = JSON[json]
hash['id'] # => "ABC"

Note I'm using JSON[json]. The JSON [] class method is smart enough to sense what the parameter being passed in is. If it's a string it'll parse the string. If it's an Array or Hash it'll serialize it. I find that handy because it allows me to write JSON[...] instead of having to remember whether I'm parsing or using to_json or something. Using it is an example of the first virtue of programmers.

Upvotes: 11

Related Questions