lc1gtq
Last Updated: February 25, 2016
·
6.549K
· sandeepleo11
789

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 = Net::HTTP::Post.new(uri.request_uri)
req.set_form_data('field1' => 'data1', 'field2' => 'data2' )          
res = Net::HTTP.start(uri.host, uri.port) do |http|
        http.request(req)
      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']
  else   
      puts res.message
  end
Say Thanks
Respond