Search code examples
jsonrubyparsingoutputhttparty

How would I parse JSON in Ruby to give me specific output


So I'm trying to make in Ruby so that it "Idk how to express myself" parse JSON from this API so the output is:

{"infected"=>19334, "deceased"=>429, "recovered"=>14047, "tested"=>515395, "tested24hours"=>8393, "infected24hours"=>351, "deceased24hours"=>11, "sourceUrl"=>"https://covid19.rs/homepage-english/", "lastUpdatedAtApify"=>"2020-07-15T14:00:00.000Z", "readMe"=>"https://apify.com/krakorj/covid-serbia"}

and I would like it to only show for example "infected"=>19334, as number 19334

I'm new to Ruby programming I'm still learning it since it's COVID pandemic and lockdown I have more of free time and it kinda makes sense to make something related to it.

This is what I've done so far:

require 'httparty'
require 'json'

url = 'https://api.apify.com/v2/key-value-stores/aHENGKUPUhKlX97aL/records/LATEST?disableRedirect=true'
response = HTTParty.get(url)
re = response.parsed_response
puts re

Solution

  • Sure, you do it like this:

    re["infected"]
     => 19334 
    

    HTTPParty parsed response returns a hash, so you access the value by the key. If the key is a "string", you access using a "string". If they key is a :symbol, you access with a :symbol.