【问题标题】:JSON parsing error in script text ruby脚本文本 ruby​​ 中的 JSON 解析错误
【发布时间】:2016-05-31 16:09:21
【问题描述】:

我正在尝试从包含存储数据的脚本文本中解析 json。它位于页面 http://www.buildbase.co.uk/storefinder 内。我正在处理的脚本文本是http://pastebin.com/embed_js/3cnewiSh,我的代码如下:

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 字符串对我来说似乎是有效的。

【问题讨论】:

  • 您能否在stores_result = 行之前添加一个简单的puts stores_jsons,以便我们可以看到它试图解析的实际JSON?
  • @PaulEllsworth 现在完成了。
  • @PaulEllsworth,嗨,保罗,我在尝试在 stores_jsons 中获取 json 字符串时更正了一个错误。你能看看吗?
  • 我认为@PaulEllsworth 的意思是使用puts 语句运行代码,然后将输出复制到您的答案中。
  • @PaulEllsworth 实际上我做不到,因为它会超出问题的字符数限制。

标签: ruby json parsing mechanize string-parsing


【解决方案1】:

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

其次,它有 HTML 标签,其中包括引号,这破坏了实际 JSON 中的引用。我抓了一个可以去掉标签的sn-p。

我不知道您需要多少数据,但这段代码确实有效。我也不确定它有多强大(例如,我刚刚用" 替换了任何\"

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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-30
    • 1970-01-01
    • 1970-01-01
    • 2023-03-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多