如何从 json 响应中多次获取相同的密钥?
How to get same key multiple times from json response?
我需要从以下响应中获取所有 "customer" 键
[
{
"customer": "Gary South",
"type": "Dealer",
"addresses":[
{
"vehicles": "CAR ",
"type": "SUV"
}
]
},
{
"customer": "William TUSK",
"type": "Reseller",
"addresses":[
{
"vehicles": "CAR ",
"type": "SUV"
}
]
},
{
"customer": "Lynn Baker",
"type": "Dealer",
"addresses":[
{
"vehicles": "VANS",
"type": "BUSINESS"
}
]
}
]
我尝试了以下代码,但它只获取第一个 'name' 键值。
result = JSON.parse(response.body)
result.each do |item|
assert_equal @customerNames, item['customer']
您忘记了 end
do
语句,您基本上需要遍历所有项目然后比较名称列表。
data = JSON.parse(response.body)
names = []
data.each do |item|
names.push(item['name'])
end
puts names
输出:
Gary South
William TUSK
Lynn Baker
我会这样做:
data = JSON.parse(response.body)
names = data.map { |elem| elem['name'] }
#=> ["Gary South", "William TUSK", "Lynn Baker"]
assert_equal @names, names
我需要从以下响应中获取所有 "customer" 键
[ { "customer": "Gary South", "type": "Dealer", "addresses":[ { "vehicles": "CAR ", "type": "SUV" } ] }, { "customer": "William TUSK", "type": "Reseller", "addresses":[ { "vehicles": "CAR ", "type": "SUV" } ] }, { "customer": "Lynn Baker", "type": "Dealer", "addresses":[ { "vehicles": "VANS", "type": "BUSINESS" } ] } ]
我尝试了以下代码,但它只获取第一个 'name' 键值。
result = JSON.parse(response.body)
result.each do |item|
assert_equal @customerNames, item['customer']
您忘记了 end
do
语句,您基本上需要遍历所有项目然后比较名称列表。
data = JSON.parse(response.body)
names = []
data.each do |item|
names.push(item['name'])
end
puts names
输出:
Gary South
William TUSK
Lynn Baker
我会这样做:
data = JSON.parse(response.body)
names = data.map { |elem| elem['name'] }
#=> ["Gary South", "William TUSK", "Lynn Baker"]
assert_equal @names, names