我有一個JSON字符串解析和循環:如何通過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
「不能得到它的工作」是非常不確定的......會發生什麼?你認爲應該發生什麼? –