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

冷暖自知 提交于 2021-01-29 05:28:37

问题


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

回答1:


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.




回答2:


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 



回答3:


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




回答4:


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..



来源:https://stackoverflow.com/questions/62916858/how-would-i-parse-json-in-ruby-to-give-me-specific-output

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!