解析在HTML文档末尾找到的JSON

时间:2013-06-09 18:03:44

标签: html ruby-on-rails json

我正试图从Readmill中提取亮点,但似乎最简单的方法是使用搜索而不是API。

结束时的

  

https://readmill.com/search?q=%22the+great+gatsby%22+%22Francis+Scott+Fitzgerald%22&filter=highlight

你找到了

<script type="text/javascript" id="page-template-data">
  App.templateData.filter = 'highlight';
App.templateData.searchResult = 

然后是一堆JSON。是否有一个方便的Rails友好的方式来解析这个JSON?

1 个答案:

答案 0 :(得分:2)

嗯,你的表面得到了帮助,搜索结果全都在一行上。现在,如果他们改变了这一点,那么这将会破裂。但是这将使用文本操作将其解压缩为JSON数组:

require 'open-uri'
require 'json'

json = {}
open('https://readmill.com/search?q=the+great+gatsby&filter=highlight').each do |line|
  if line =~ /App.templateData.searchResult/
    json = JSON.parse line.sub('App.templateData.searchResult = ','').strip.to_s[0..-2]
    break
  end
end

puts json.map{|j| j["title"] }
 => “Gatsby?” demanded Daisy. “What Gatsby?”
    ...