脚本文本ruby中的JSON解析错误

问题描述:

我想从包含存储数据的脚本文本解析json。它位于页面http://www.buildbase.co.uk/storefinder内。对此我身边工作的脚本文本是http://pastebin.com/embed_js/3cnewiSh和我的代码如下:脚本文本ruby中的JSON解析错误

stores_url = "http://www.buildbase.co.uk/storefinder" 
mechanize = Mechanize.new 
stores_page = mechanize.get(stores_url) 
stores_script_txt = stores_page.search("//script[contains(text(), 'storeLocator.initialize(')]")[0].text 
stores_jsons = stores_script_txt.split("storeLocator.initialize($.parseJSON('{\\\"all\\\":")[-1].split(",\\\"selected\\\":0}') ,\tfalse);\n  });")[0] 
puts stores_jsons 
stores_result = JSON.parse(stores_jsons) 

的JSON.parse给我的错误是:

from /home/private/.rvm/gems/ruby-2.1.5/gems/json-1.8.3/lib/json/common.rb:155:in `parse' 
from /home/private/.rvm/gems/ruby-2.1.5/gems/json-1.8.3/lib/json/common.rb:155:in `parse' 
from (irb):240 
from /home/private/.rvm/rubies/ruby-2.1.5/bin/irb:11:in `<main>' 

我不知道我要去的地方错误,因为JSON字符串似乎对我有效。

+0

你可以添加一个简单的'把stores_jsons'的'stores_result ='行之前,所以我们可以看到实际的JSON它的尝试解析? –

+0

@PaulEllsworth现在完成。 –

+0

@PaulEllsworth,你好保罗我试图在stores_jsons中获得json字符串时纠正了一个错误。你能看到吗? –

有几个问题。首先,您收到的文本格式不正确,因为它使用“而不是引号”等。

其次,它包含HTML标记,其中包含引号,这会在实际的JSON中打乱引号。我抓住了一个只是去掉标签的代码片段

我不知道你需要多少数据,但是这个代码确实有用,我也不确定它有多强大(例如,我只是用"对于任何\"

require 'mechanize' 
stores_url = "http://www.buildbase.co.uk/storefinder" 
mechanize = Mechanize.new 
stores_page = mechanize.get(stores_url) 
stores_script_txt = stores_page.search("//script[contains(text(), 'storeLocator.initialize(')]")[0].text 
stores_jsons = stores_script_txt.split("storeLocator.initialize($.parseJSON('{\\\"all\\\":")[-1].split(",\\\"selected\\\":0}') ,\tfalse);\n  });")[0] 
stores_jsons = stores_jsons.gsub('\"', '"').gsub(/<\/?[^>]*>/, '').gsub(/\n\n+/, "\n").gsub(/^\n|\n$/, '') 
stores_result = JSON.parse(stores_jsons)