2013-04-14 47 views
1

我想解析輸出一些Ruby中的JSON值,但我不斷收到意想不到的結果。Ruby JSON解析輸出計數

articlelist = client.get('/v1/my_data/articles') 
#debug 
puts (articlelist.body) 

#Parse the article list and get values 
parsed = JSON.parse(articlelist.body) 
puts parsed.count 

parsed.count do 
    |currentfile| 
    inputfile = File.open ('file.example')#file.example should be replaced with local file 
    filehash = OpenSSL::Digest.new('sha256', 'inputfile') 
    puts "#{inputfile} has #{filehash.name} hash of #{filehash}"#debug 
end 

我得到以下結果:

{"count": 0, "items": []} 
2 
#<File:0x00000001a83b48> has SHA256 hash of 3de6c8f12dc4c9efe67c0a5bbfe21502cde5ee22e7ef0bc8d348c696db9a4363 
#<File:0x00000001a83238> has SHA256 hash of 3de6c8f12dc4c9efe67c0a5bbfe21502cde5ee22e7ef0bc8d348c696db9a4363 

如果count值爲零,爲什麼它給我的2計數值(inputfile中只是局部的示例文件)?

回答

1

parsed是一個具有兩個元素的散列,所以parsed.count2。另一方面,parsed['count']0

+0

那麼'count'是任何通用ruby對象的方法嗎?我可能應該知道這一點。謝謝! – user2276204

+1

像哈希和陣列的集合對象有它。我猜你是來自JavaScript,其中'parsed.count'和'parsed ['count']'意味着同樣的事情。在Ruby中,只能使用後一種形式訪問哈希元素,而前一種形式會調用該對象的方法。 –