没有将String隐式转换为Integer(TypeError)

时间:2014-06-14 17:49:12

标签: ruby json

我正在尝试使用ruby解析一行JSON并遇到此错误

没有将String隐式转换为Integer(TypeError)

uri = URI.parse('xxx')

http = Net::HTTP.new(uri.host, uri.port)
request = Net::HTTP::Get.new(uri.request_uri)

response = http.request(request)

if response.code == "200"
  result = JSON.parse(response.body)

  result.each do |doc|
    #if doc.is_a?(Hash)
      dns_name = doc['dns_name'] #reference properties like this  <-- Line 25 (see below)
      host = ['host']# this is the result in object form
      #end
  end
else
  puts "ERROR!!!"
end

puts host
puts dns_name

我看了几个类似的问题,但似乎没有帮助,我尝试过改变

      result.each do |doc|

      result.each.first do |doc|

正如他们所讨论的那样。

我的红宝石充其量是可以通行的,但我也会链接到一些文档,我已经尝试过官方文档而没有太多运气。这是返回的内容:            [{"name":"server","power_state":"On","host":"host","cluster":"cluster","ip_address":"10.0.0.0","dns_name":"server.com","vcenter":"vcenter","description":" ","datastore":"datastore","num_vcpu":"2","mem_size_gb":8,"vmid":"1","application":"Misc","business_unit":"","category":"","support_contact":"joe@example.com"},200]

我也试过.is_a?(哈希)和.is_a?(数组)。我相当肯定当我看到json时它是一个哈希数组,问题在于我在回到行尾的200响应代码。为什么这是一个我不知道的问题,我想解决它,但json是由一个已知​​的源生成的,所以如果我能证明它有问题,我可以让它们修改它。

由于

更新

从错误中全面询问

'./ status.rb:25:在`[]''

'./ status.rb:25:在'block in''

'。/ status.rb:23:在'each''

'。/ status.rb:23:在'''

2 个答案:

答案 0 :(得分:3)

在你的情况下,它似乎并不像是循环的原因,你可以写:

dns_name = result.first['dns_name']
host = result.first['host']

因为result是一个数组,其中2个对象0是Hash,1是一个应该工作的Int。

答案 1 :(得分:0)

如果格式化JSON,它将如下所示:

[
    {
        "name":"server",
        "power_state":"On",
        "host":"host",
        "cluster":"cluster",
        "ip_address":"10.0.0.0",
        "dns_name":"server.com",
        "vcenter":"vcenter",
        "description":" ",
        "datastore":"datastore",
        "num_vcpu":"2",
        "mem_size_gb":8,
        "vmid":"1",
        "application":"Misc",
        "business_unit":"",
        "category":"",
        "support_contact":"joe@example.com"
    },
    200
]

您想要访问哈希,它是数组中的第一个元素,所以:

if response.code == "200"
  result = JSON.parse(response.body)
    dns_name = result.first['dns_name']
    host = result.first['host']
else
  puts "ERROR!!!"
end

无需each