将json输出到字符串

时间:2014-05-07 17:46:38

标签: ruby json string

我一直在教自己红宝石,但现在我遇到了一个问题,我一直收到错误:

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"]

2 个答案:

答案 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通道配对的内容:

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"]]

答案 1 :(得分:1)

之前的回答表明您的TypeError来自

pjson = JSON[response.body]

事实并非如此;它来自

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

JSON[x]JSON.parse(x)可以互换。

抛出TypeError是因为pjson是一个数组,而不是一个散列,只接受整数位置(例如pjson[0])。 pjson是一个数组,因为原始json文本只有一个顶级哈希对象,它嵌套在一个数组中(最初的&#34; [&#34;)。

此外,正如迈克尔的回答所指出的,"watt"不是"sensor"的子项 - 它是顶级哈希中的关键字。所以你想要的是pjson[0]获取你的哈希对象,然后pjson[0]["watt"]得到"watt"的值(在这种情况下,&#34; 703&#34;)。

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