gpt4 book ai didi

ruby - 将json输出为字符串

转载 作者:太空宇宙 更新时间:2023-11-03 17:51:50 25 4
gpt4 key购买 nike

我一直在自学 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"]

最佳答案

为清楚起见,我建议使用 JSON.parse而不是 the [] operator method .

pjson = JSON.parse response.body

key watt 不是 sensor 的子 key 。它是父数组元素的子键。外层 [] 表示一个数组,并且至少有一个数字键。

因此,您可以通过以下方式直接检索 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"]]

关于ruby - 将json输出为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23524677/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com