2016-01-12 60 views
0

我有一個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 
+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 
0

如果你想遍歷的風格的數組,它是常見的用C即使用數組索引,你應該索引的AR時做到像

urls = domain['urls'] 
(0..urls.length).each do |i| 
    puts " URL: #{urls[i]}" 
end 

,或者至少辦案當代碼嘗試訪問超出數組中輸入的數據時,ray元素返回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 
+2

*爲什麼* OP應該這樣做?不要拋出代碼,解釋爲什麼應該以某種方式完成某件事,以便能夠建立它。 –