通常,在HTML頁面中的JSON響應沒有編碼或包含,它返回一個字符串,它包括整個身體:
require 'open-uri'
open('http://httpbin.org/headers').read
# => "{\n" +
# " \"headers\": {\n" +
# " \"Accept\": \"*/*\", \n" +
# " \"Accept-Encoding\": \"gzip;q=1.0,deflate;q=0.6,identity;q=0.3\", \n" +
# " \"Host\": \"httpbin.org\", \n" +
# " \"User-Agent\": \"Ruby\"\n" +
# " }\n" +
# "}\n"
解析該回Ruby對象是容易的:
require 'json'
require 'open-uri'
JSON[open('http://httpbin.org/headers').read]
# => {"headers"=>
# {"Accept"=>"*/*",
# "Accept-Encoding"=>"gzip;q=1.0,deflate;q=0.6,identity;q=0.3",
# "Host"=>"httpbin.org",
# "User-Agent"=>"Ruby"}}
JSON[...]
是一個簡單,通用的方法來解析JSON字符串,或序列化Ruby對象。它是足夠聰明,知道做哪一種方式:
require 'json'
foo = {'a' => 1}
foo.class # => Hash
bar = JSON[foo] # => "{\"a\":1}"
bar.class # => String
baz = JSON[bar] # => {"a"=>1}
baz.class # => Hash
如果你想更明確的,你可以使用to_json
和parse
方法:
require 'json'
foo = {'a' => 1}
bar = foo.to_json # => "{\"a\":1}"
baz = JSON.parse(bar) # => {"a"=>1}
注意,在任何時候被引入nokogiri必要的。
如果,理由很奇怪,JSON注入到頁面,或者你想獲得一些JavaScript的數據,這是一個更容易的事情,你可以使用引入nokogiri:
require 'json'
require 'nokogiri'
html = <<EOT
<html>
<head>
<script>
var foo = '{"a":1}';
</script>
</head>
</html>
EOT
doc = Nokogiri::HTML(html)
script_contents = doc.at('script').text # => "\n var foo = '{\"a\":1}';\n "
foo = JSON[script_contents[/({.+})/, 1]] # => {"a"=>1}
foo.class # => Hash
老實說,我認爲nokogirl是在這種情況下使用的。我無法讓faraday工作,但是httparty工作。謝謝! – Sylar
Ruby有許多有用的HTTP客戶端。有關列表,請參閱https://www.ruby-toolbox.com/categories/http_clients。 –
@theTinMan我嗨嗨剛剛試過你的答案,那也工作。謝謝,但在這個階段我的知識似乎有所進步 – Sylar