[英]Iterate through json response and return one array
下面的代碼以字符串的形式返回所有縣,我可以通過使用inspect方法看到。
def self.all_counties
response['ChargeDevice'].each do |charger|
puts ['ChargeDeviceLocation']['Address']['County'].inspect
end
end
什么是將每個返回的字符串存儲在一個數組中以便以后可以進行操作的正確方法?
JSON格式
"ChargeDeviceLocation" => {
"Latitude" =>"51.605591",
"Longitude" =>"-0.339510",
"Address" => {
"County" =>"Greater London",
"Country" =>"gb"
}
如果響應具有每個項目的所有鍵,則此方法有效:
counties = response['ChargeDevice'].map do |r|
r.dig('ChargeDeviceLocation', 'Address', 'County')
end
當樹沒有所有項目的條目時,類似這樣的操作將使您無用:
counties = response['ChargeDevice'].map do |r|
r.fetch('ChargeDeviceLocation', {}).
fetch('Address', {}).
fetch('County', nil)
end
您還可以使用JSONPath (和ruby JSONPath gem )。
require 'jsonpath'
counties = JsonPath.new('$..County').on(response.to_json)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.