我正在尝试迭代下面的JSON,但我收到了错误
./test.rb:39:in `[]': can't convert String into Integer (TypeError)
from ./test.rb:39:in `block in <main>'
from ./test.rb:38:in `each'
from ./test.rb:38:in `<main>'
从此代码(第39行= print child ['data'] ['body'])
有谁能告诉我我做错了什么?
data = JSON.parse(res.body)
38 data.each do |child|
39 print child['data']['body']
40 end
以下是res.body:
{ "views": [ "Logs_Messages","Content_Sources","Bitrates_HD_Encoder","Hardware_Status_eCMM","Bitrates_Per_Program","Content_OOB_SI","Debug_Dump","Hardware_Status_In_Band_Tuners","Alarms_Current","Version_Information","Software_Status_License","Hardware_Status_Module_Presence","Reboot","Content_Mappings","Logs_Persistent","Content_Routing","Software_Status_Transcoder_Enabled","Software_Status_Code_Download","Decryption_Identification","Hardware_Status_System_Monitoring","Software_Status_Operating_System_Stats","Software_Status_TLV","Hardware_Status_Out_of_Band_Tuner","Content_EPG","Hardware_Status_HD_Encoders","Alarms_History","Bitrates_Output","Decryption_Status","Bitrates_Input","Software_Status_EPG_Download","Interfaces","Hardware_Status_Output_Module"] }
答案 0 :(得分:0)
在第38行的示例中,data
应为res.body
的内容。
如果我们查看您说res.body
的散列,我们可以看到它是一个带有一个键的散列,#34; views&#34;,并且该键指向一个值数组。
到目前为止,我还不确定您要使用脚本实现的目标。我猜你正在尝试打印出阵列中的每个项目。为此,您需要执行以下操作:
data = JSON.parse(res.body)
data["views"].each do |view|
print view
end
这将访问存储在数组views
中的键data
处的值,然后循环遍历该数组中的值,并将其打印出来。
请告诉我这是否有帮助!