2

您好,我使用 HTTParty 调用远程 json 文件,我需要提取 URL 以在我的一个测试中使用。json 格式类似于:

  "manifest" : {
    "header" : {
      "generated" : "xxxxxxxxxxxxxxx",
      "name" : "xxxxxxxxxxx",
      "version" : "1.0.0"
    },
    "files" : [ {
      "file" : "blimp.zip",
      "url" : "http://www.xxx.xx/restaurants_blimp.zip",
      "checksum" : "ee98c9455b8d7ba6556f53256f95"
    }, {
      "file" : "yard.zip",
      "url" : "www.xxx.xx/yard.zip",
      "checksum" : "e66aa3d123f804f34afc622b5"
    }

在 irb 上,我可以获取示例中的所有子哈希: ['manifest']['files'] 并且只有在我指定哪个 .. 例如 puts file['manifest']['files' 时才能获取 url ]['1']['url'] <-- 这确实适用于 irb,但由于我需要获取所有 url,这就是我使用 .each 的原因,但它让我无法转换为字符串错误或类似错误

#!/usr/bin/env ruby

require 'httparty'

HOST=ARGV[0]
ID=ARGV[1]
VERSION=ARGV[2]


class MyApi
  include HTTParty
end

file = MyApi.get("http://#{HOST}/v1/dc/manifest/#{ID}/#{VERSION}")


file.each do |item|
 puts item['manifest']['files']['url']
end

不工作,但我可以在 IRB 上做一个:

puts item['manifest']['files'][2]['url'] <-- 这会给我 url 但是 .each 只会抱怨不能转换为字符串或类似的

4

2 回答 2

3

尝试以下操作:

#!/usr/bin/env ruby

require 'httparty'

(HOST, ID, VERSION) = ARGV

class MyApi
  include HTTParty
  format :json
end

response = MyApi.get("http://#{HOST}/v1/dc/manifest/#{ID}/#{VERSION}")

puts response.inspect

添加的format :json告诉 HTTParty 将响应解析为 JSON。然后你会得到一个可以正确迭代的哈希。

于 2012-03-22T00:57:14.727 回答
2

尝试:

file['manifest']['files'].each do |item|
   puts item['url']
end
于 2012-03-21T23:49:22.037 回答