0

有没有更有效的方法来完成这项工作?我的意思是我可以重构我的脚本以更有效地获得结果,而不是从其他来源获取此信息,即。亚马逊通过 API 或 SDK。

我做了一个返回这个的卷曲

{
         "instanceId" : "i-123abcde",
         "billingProducts" : null,
         "version" : "2001-01-01",
         "accountId" : "123456789012",
         "instanceType" : "m1.large",
         "architecture" : "x86_64",
         "kernelId" : "aki-123ab1ab",
         "ramdiskId" : null,
         "pendingTime" : "2001-01-00T00:00:00Z",
         "availabilityZone" : "us-east-1a",
         "imageId" : "ami-12345ab1",
         "devpayProductCodes" : null,
         "privateIp" : "10.10.10.10",
         "region" : "us-east-1"
         }

这是我的代码块

require 'rubygems'
require 'curb'
require 'pp'

info = Curl.get("http://169.254.169.254/latest/dynamic/instance-identity/document")

foo = info.body_str.split(',').join.scan(/"(.*?)" : "(.*?)"/)

quux = {}
foo.each do |baz|
        quux[baz[0]] = baz[1]
end
pp quux

结果是带有键的散列

{
         "instanceId" => "i-123abcde",
         "version" => "2001-01-01",
         "accountId" => "123456789012",
         "instanceType" => "m1.large",
         "architecture" => "x86_64",
         "kernelId" => "aki-123ab1ab",
         "pendingTime" => "2001-01-00T00:00:00Z",
         "availabilityZone" => "us-east-1a",
         "imageId" => "ami-12345ab1",
         "privateIp" => "10.10.10.10",
         "region" => "us-east-1"
         }
4

1 回答 1

2

那是JSON数据。做这个:

require 'json'
...
quux = JSON.parse(info.body_str)
于 2013-01-24T20:00:32.920 回答