首页 > 解决方案 > 我将如何在 Ruby 中解析 JSON 以提供特定的输出

问题描述

所以我试图在 Ruby 中制作,以便它“Idk 如何表达自己”从这个 API 解析 JSON,所以输出是:

{"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"}

我希望它只显示为例如"infected"=>19334,数字19334

我是 Ruby 编程的新手,我还在学习它,因为它是 COVID 大流行和封锁,我有更多的空闲时间,做一些与它相关的东西有点道理。

这是我到目前为止所做的:

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

标签: jsonrubyparsingoutputhttparty

解决方案


不完全确定这是否是您的问题,但parsed_response已经解析了 json 并将其转换为哈希。

所以要访问该infected领域,你可以这样做

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

推荐阅读