Monday, October 29, 2012

Get a particular key value from json in ruby

if you are getting a json response like this

res  = {"status":0,"result":{"tuid":5851,"title":"300312577_abc.xls"}}

to extract status and 'tuid' from this

#!/usr/bin/env ruby

require 'rubygems'
require 'json'

res  = {"status":0,"result":{"tuid":5851,"title":"300312577_abc.xls"}}

puts status = JSON.parse(res)['status']

puts tuid = JSON.parse(res)['result']['tuid']

for example if you are using net/http

uri = URI.parse("some_url")
req =
req.set_form_data('field1' => 'data1', 'field2' => 'data2' )          
res = Net::HTTP.start(, uri.port) do |http|
          endcase res
     when Net::HTTPSuccess, Net::HTTPRedirection
          puts "OK"
          puts res.body
          puts status = JSON.parse(res.body)['status']
          puts tuid = JSON.parse(res.body)['result']['tuid']
          puts res.message