我正在编写一个简短的Ruby程序,它将采用一个邮政编码并返回该邮政编码2英里范围内的城市名称.我成功调用了API并能够解析JSON数据,但我不确定如何访问"city"键.
url = API call (not going to replicate here since it requires a key)
uri = URI(url)
response = Net::HTTP.get(uri)
JSON.parse(response)
Run Code Online (Sandbox Code Playgroud)
这是我的JSON的样子.
{
"results": [
{
"zip": "08225",
"city": "Northfield",
"county": "Atlantic",
"state": "NJ",
"distance": "0.0"
},
{
"zip": "08221",
"city": "Linwood",
"county": "Atlantic",
"state": "NJ",
"distance": "1.8"
}
]
}
Run Code Online (Sandbox Code Playgroud)
我一直试图像这样访问'城市':
response['result'][0]['city']
Run Code Online (Sandbox Code Playgroud)
这似乎是不正确的.也试过了
response[0][0]['city']
Run Code Online (Sandbox Code Playgroud)
以及相同代码的其他几种排列.
如何从JSON数据中获取值'Northfield'?
你几乎就在那里,只需使用results而不是result结果JSON.parse(response)而不是response:
JSON.parse(response)["results"][0]["city"]
#=> "Northfield"
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
219 次 |
| 最近记录: |