我有一个JSON字符串:
{
"normal_domains":[{
"urls [
"domain1.com",
"domain2.com"
],
"id":3,
"find":"ama",
"type":"text"
}
],
"premium_domains":[{
"urls":[
"domain3.com",
"domain4.com"
],
"id":1,
"find":"amg",
"type":"text"
}
]
}
我想为散列中的每个域输出一个列表,其中包含相应的属性:
Domain type: normal_domains
Domain: domain3.com
ID: 3
Find: ama
-- for each domain --
我的代码就是这个,但我无法让它运转起来。它返回NoMethodError: undefined method [] for nil:NilClass
:
from_api = '{"normal_domains":[{"urls":["domain1.com","domain2.com"],"id":3,"find":"ama","type":"text"}],"premium_domains":[{"urls":["domain3.com","domain4.com"],"id":1,"find":"amg","type":"text"}]}'
result = JSON.parse from_api
result.each do |child|
loop_index = 0
child.each do |sub_child|
puts "Domain type: #{child}"
puts "Domain: #{sub_child[loop_index]['urls']}"
puts "ID: #{sub_child[loop_index]['id']}"
puts "Find: #{sub_child[loop_index]['find']}"
loop_index += 1
end
end
答案 0 :(得分:1)
从JSON.parse
返回的哈希没有.each
方法。
以更有条理的方式设想您的输入哈希:
{
"normal_domains":[ {
"urls [
"domain1.com",
"domain2.com"
],
"id":3,
"find":"ama",
"type":"text"
}],
"premium_domains":[{
"urls":[
"domain3.com",
"domain4.com"
],
"id":1,
"find":"amg",
"type":"text"
}]
}
你的代码应该是:
result = JSON.parse from_api
result.keys.each do |domain_type|
childArray = result[domain_type]
childArray.each do |child|
urls = child["urls"]
urls.each do |url|
puts "Domain type: #{domain_type}"
puts "Domain: #{url}"
puts "ID: #{child['id']}"
puts "Find: #{child['find']}"
end
end
end
答案 1 :(得分:0)
如果要以C中常见的样式迭代数组,即使用数组索引,则应该像
那样进行迭代urls = domain['urls']
(0..urls.length).each do |i|
puts " URL: #{urls[i]}"
end
或至少处理索引数组元素的情况,当代码尝试访问超出数组输入数据的数据时返回nil
。由于可以使用迭代器,因此通常不需要使用数组索引。
使用迭代器,不需要索引,也不需要检查访问是否超出容器的边界。
result.each do |key,value|
puts "Domain type: #{key}"
value.each do |domain|
id = domain['id']
find = domain['find']
type = domain['type']
puts " ID: #{id}"
puts " Find: #{find}"
puts " Type: #{type}"
domain['urls'].each do |url|
puts " URL: #{url}"
end
end
end