I have this code:

uri =URI.parse('http://finance.google.com/finance/info?client=i&q=NSE:ANDHRABANK')

rs = Net::HTTP.get(uri)

rs.delete! '//'

a = JSON.parse(rs) 
p a

It's output is:

[{"id"=>"15355585", "t"=>"ANDHRABANK", "e"=>"NSE", "l"=>"49.30", "l_fix"=>"49.30", "l_cur"=>"₹49.30", "s"=>"0", "ltt"=>"3:30PM GMT+5:30", "lt"=>"Jan 13, 3:30PM GMT+5:30", "lt_dts"=>"2017-01-13T15:30:00Z", "c"=>"-0.15", "c_fix"=>"-0.15", "cp"=>"-0.30", "cp_fix"=>"-0.30", "ccol"=>"chr", "pcls_fix"=>"49.45"}]

I am not able to access data from this JSON array. I want to access the data like a['t'].

3 Answers

Avijit Majhi On Best Solutions

Either you run loop on array then you can access using a[i]["t"] or use a[0]["t"].

Note: i is the index of array elements.

orde On

Since you're dealing with a hash in an array, you have to specify the array element position as well:

require 'json'
require 'net/http'

uri = URI.parse('http://finance.google.com/finance/info?client=i&q=NSE:ANDHRABANK')
rs = Net::HTTP.get(uri)
rs.delete! '//'

a = JSON.parse(rs) 
p a.class             #=> Array
p a[0]["t"]           #=> "ANDHRABANK"
the Tin Man On

You aren't making it easy for yourself. Consider this:

require 'json'
require 'open-uri'

rs = open('http://finance.google.com/finance/info?client=i&q=NSE:ANDHRABANK').read
foo = JSON[rs[4..-1]].first
foo['t'] # => "ANDHRABANK"
  1. Rather than deal with the intricacies of Net::HTTP, which is more useful as a tool to build new HTTP services, I'd recommend relying on OpenURI, or one of the many HTTP clients available. The advantage over Net::HTTP is redirection is automatically handled plus simplicity. OpenURI does have some downsides, but for a basic URL getter it's fine.

  2. The JSON class has [] which is smart enough to convert a string into the corresponding Ruby object. It'll also serialize a Ruby object back into a String:

    puts JSON[{'a' => 1}]
    # >> {"a":1}
  3. The service you're calling is returning JSON, only, in this case, it's a single-element array containing a hash. Using first makes it easy to retrieve the hash and access it normally. It's cleaner to do that than to sprinkle your code with this form:


    which is longer to type and results in a visual noise.