Viktor YT
Viktor YT

Reputation: 21

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

Upvotes: 0

Views: 160

Answers (4)

Muhammad Adeel
Muhammad Adeel

Reputation: 79

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 

At this stage we have that output

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

You can access any above variable value like that

infected = re["infected"]
deceased = re["deceased"]

And so on..

Upvotes: 0

Segrelove
Segrelove

Reputation: 19

Personnaly, I prefer using 'open-uri'.

require 'open-uri'
require 'json'

url = 'https://api.apify.com/v2/key-value-stores/aHENGKUPUhKlX97aL/records/LATEST?disableRedirect=true'
response = open(url)
json = JSON.parse(response)

puts json["infected"]

-> output 19334

Upvotes: 0

nathanvda
nathanvda

Reputation: 50057

Not entirely sure if that is your question, but parsed_response has already parsed the json and converted it into a hash.

So to access the infected field, you can just do

 re = response.parsed_response
 infected = re["infected"]
 puts infected 

Upvotes: 1

benjessop
benjessop

Reputation: 1959

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.

Upvotes: 0

Related Questions