我一直在自学ruby,但现在遇到了一个问题,我不断地遇到一个错误:
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"]
最佳答案
前面的答案指出您的TypeError来自行
pjson = JSON[response.body]
不是这样的,而是来自
p pjson["sensor"]["watt"].
JSON[x]
和JSON.parse(x)
可以互换。抛出TypeError是因为pjson是一个数组,而不是散列,并且只接受整数位置(例如
pjson[0]
)pjson
是一个数组,因为原始json文本只有一个顶级散列对象,但它嵌套在一个数组中(初始“[”)。另外,正如michael的回答所指出的,
"watt"
不是"sensor"
的子键——它是顶级散列中的键。因此,您需要的是pjson[0]
获取散列对象,然后pjson[0]["watt"]
获取"watt"
的值(在本例中为“703”)。 pjson[0]['watt']
=> "703"