gpt4 book ai didi

arrays - 遍历 Ruby 中的哈希数组(解析 JSON)

转载 作者:太空宇宙 更新时间:2023-11-03 17:20:18 24 4
gpt4 key购买 nike

我有这个哈希数组,它是在执行 API 调用并通过 JSON.parse 运行它时创建的:

{
"results": [
{
"zip": "08225",
"city": "Northfield",
"county": "Atlantic",
"state": "NJ",
"distance": "0.0"
},
{
"zip": "08221",
"city": "Linwood",
"county": "Atlantic",
"state": "NJ",
"distance": "1.8"
}
]
}

我试图从每个对象中获取所有邮政编码并将它们放入一个数组中:

zipcode_array = Array.new

我试过下面的代码:

locations.each do |zipcode|
zipcode_array.push(['results'][i]['zip'])
end

我希望我的最终输出是:

zipcode_array = ["08225", "08221"]

有人对我遗漏的东西有任何提示吗?

最佳答案

你的代码似乎缺少这里的i变量(索引),但实际上你不需要它,因为你总是可以使用map函数来实现地道的Ruby代码:

require "json"

response = '{
"results": [
{
"zip": "08225",
"city": "Northfield",
"county": "Atlantic",
"state": "NJ",
"distance": "0.0"
},
{
"zip": "08221",
"city": "Linwood",
"county": "Atlantic",
"state": "NJ",
"distance": "1.8"
}
]
}'

parsed_response = JSON.parse(response)
zipcode_array = parsed_response["results"].map { |address| address["zip"] }

关于arrays - 遍历 Ruby 中的哈希数组(解析 JSON),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49839007/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com