2014-05-07 60 views
1

我一直都自學Ruby,但現在我已經incouted一個問題,我不斷收到一個錯誤:outputing JSON字符串

mesureitcurrentv.rb:9:in `[]': can't convert String into Integer (TypeError) 
from mesureitcurrentv.rb:9:in `<main>' 

,我似乎無法修復代碼。

JSON:

[{"sensor":{"x":"","sensor_id":"0","sensor_title":"sensor 0","sensor_clamp":"0","position_id":"1","position_time":"2013-10-13 17:38:39","position_description":"start position","position_sensor":"0","measure_history":"365","measure_currency":"Pound","measure_sensor":"0","measure_range":"","measure_timeframe":"0","measure_timezone":"GMT0","measure_timezone_diff":"0","measure_type":"0","measure_pvoutput_id":"0","measure_pvoutput_api":"","positions":{"1":{"position":"1","time":"2013-10-13 17:38:39","description":"start position"}}},"tmpr":"20.5","watt":"703","daily":"13.86 Kwh<br \/>2.13","hourly":"0.47 Kwh<br \/>0.07","weekly":"112.748 Kwh<br \/>17.35","monthly":"506.063 Kwh<br \/>77.88"}] 

代碼:

#!/usr/bin/env ruby 
require 'net/http' 
require 'json' 


http = Net::HTTP.new("192.168.1.11") 
response=http.request(Net::HTTP::Get.new("/php/measureit_functions.php?do=summary_start")) 
pjson = JSON[response.body] 
p pjson["sensor"]["watt"] 
+1

也許'pjson [0] [ 「傳感器」] [ 「瓦特」]' – zishe

+0

出來作爲零 –

回答

1

前面的回答中指出你的類型錯誤從線路

pjson = JSON[response.body] 

這是不是這樣的未來;它是從

p pjson["sensor"]["watt"]. 

JSON[x]JSON.parse(x)是可互換的到來。

TypeError被拋出,因爲pjson是一個數組而不是散列,並且只接受整數位置(例如pjson[0])。 pjson是一個數組,因爲雖然原始json文本只有一個頂級哈希對象,但它嵌套在數組中(最初的「[」)。

此外,正如邁克爾的回答指出的,"watt"不是"sensor"的子項 - 它是頂級散列中的關鍵。所以你想要的是pjson[0]得到你的散列對象,然後pjson[0]["watt"]得到"watt"(在這種情況下,「703」)的值。

pjson[0]['watt'] 
    => "703" 
+0

從來不知道'JSON#[]'存在爲一種方法,但是[那裏它是在文檔中](http://www.ruby-doc.org/stdlib-2.0.0/libdoc/json/rdoc/JSON.html#method-i-5B-5D) –

+0

對不起,在白天的學校,因爲得到輪到標記答案 –

3

爲清楚起見,我會建議使用的JSON.parse代替the [] operator method

pjson = JSON.parse response.body 

關鍵watt不是sensor一個子項。它是父數組元素的子項。外[]意味着一個數組,並至少有一個數字鍵。

所以直接

,您可以檢索通過watt

# watt is a key of the array element [0] 
pjson[0]['watt'] 
=> "703" 

但更有力,你可以檢索通過所有這些配對他們sensor_id S,如果你希望有一個以上的數組元素返回:

pjson.map { |s| [s['sensor']['sensor_id'], s['watt']] } 

將返回一個數組的數組等

[["0", "703"]] 

或者與sensor_title

pjson.map { |s| [s['sensor']['sensor_title'], s['watt']] } 
=> [["sensor 0", "703"]]