0

如何使用 ruby​​ 从 JSON 响应中提取所有 URL?我有一个返回 JSON 的 URL (test.testurl.de/test?p=12),例如

...
images: [
{
path: "http://static.mydomain.de/pics/z.jpg",
format: "image/jpeg",
},
{
path: "http://static.mydomain.de/pics/y.jpg",
format: "image/jpeg",
},
{
path: "http://static.mydomain.de/pics/x.jpg",
format: "image/jpeg",
},
...

如果我尝试通过以下方式提取:

test = open("test.testurl.de/test?p=12").read
puts URI.extract(test)

然后我得到:

["http:", "http:", "http:"]

谁能告诉我为什么我不会得到整个网址?

谢谢

4

2 回答 2

0

我建议使用 HTTP 客户端,例如 HTTParty、Typhoeus 或更好的 Faraday。

但是,如果您想自己滚动,请使用 JSON gem 来解析响应,例如:

response = open("test.testurl.de/test?p=12").read
parsed = JSON.parse(response) rescue {}
parsed['images'].map { |image| image['path'] }
于 2013-09-05T21:31:19.307 回答
0
images: [
{
path: "http://static.mydomain.de/pics/z.jpg",
format: "image/jpeg",
},
...
...

您的字符串不是 json,因此您无法将其解析为 json。这真的是返回的吗?

如果我尝试通过以下方式提取:

test = open("test.testurl.de/test?p=12").read
puts URI.extract(test)

然后我得到:

["http:", "http:", "http:"]

我得到不同的东西:

require 'uri'

str =<<END_OF_JUNK
images: [
  {
    path: "http://static.mydomain.de/pics/z.jpg",
    format: "image/jpeg", 
  },

  {
    path: "http://static.mydomain.de/pics/y.jpg",
    format: "image/jpeg",
  },

  {
    path: "http://static.mydomain.de/pics/x.jpg",
    format: "image/jpeg",
  }
]
END_OF_JUNK

p URI.extract(str)


--output:--
["path:", "http://static.mydomain.de/pics/z.jpg", "format:", "path:", "http://static.mydomain.de/pics/y.jpg", "format:", "path:", "http://static.mydomain.de/pics/x.jpg", "format:"]

有了这个输出,我可以做到:

results = results.select do |url|
  url.start_with? "http"
end

p results

--output:--
["http://static.mydomain.de/pics/z.jpg", "http://static.mydomain.de/pics/y.jpg", "http://static.mydomain.de/pics/x.jpg"]

但是,如果您发布的内容是转换为 json 的 ruby​​ 哈希的一部分:

require 'json'
require 'uri'

hash = {
  images: [
    {
      path: "http://static.mydomain.de/pics/z.jpg",
      format: "image/jpeg", 
    },

    {
      path: "http://static.mydomain.de/pics/y.jpg",
      format: "image/jpeg",
    },

    {
      path: "http://static.mydomain.de/pics/x.jpg",
      format: "image/jpeg",
    }
  ]
}

str = JSON.dump(hash)
p str

--output:--
"{\"images\":[{\"path\":\"http://static.mydomain.de/pics/z.jpg\",\"format\":\"image/jpeg\"},{\"path\":\"http://static.mydomain.de/pics/y.jpg\",\"format\":\"image/jpeg\"},{\"path\":\"http://static.mydomain.de/pics/x.jpg\",\"format\":\"image/jpeg\"}]}"

然后你可以这样做:

results = URI.extract(str)
p results

--output:--
["http://static.mydomain.de/pics/z.jpg", "http://static.mydomain.de/pics/y.jpg", "http://static.mydomain.de/pics/x.jpg"]
于 2013-09-05T23:27:48.723 回答