ruby - 如何解析抓取的 JSON 字符串

标签 ruby regex ruby-on-rails-3 xpath mechanize

我需要获取存储在脚本标记中的函数中的 JSON 字符串的值,如下所示:

<script type="text/javascript">
    my.function("bar", {"foo1": false, "foo2": true, "foo3": "foobar!"});
</script>

我可以像这样使用 Mechanize 获取特定标签:

parser.xpath("//script[ contains(text(), 'my.function')]").text

但我不确定如何从那里继续。如何提取字符串的 JSON 部分并将其转换为哈希值以便提取值?

最佳答案

这是一个纯 XPath 1.0 解决方案:

使用:

concat('{',
       substring-before(
               substring-after(
                   substring-after(., 'my.function('),
                  '{'
                               ),
               ');'
                        )
       )

基于 XSLT 的验证:

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output method="text"/>

 <xsl:template match="/">
  <xsl:copy-of select=
   "concat('{',
           substring-before(
                   substring-after(
                       substring-after(., 'my.function('),
                      '{'
                                   ),
                   ');'
                            )
           )
   "/>
 </xsl:template>
</xsl:stylesheet>

当此转换应用于提供的 XML 文档时:

<script type="text/javascript">
 my.function("bar", {"foo1": false, "foo2": true, "foo3": "foobar!"});
</script>

对 XPath 表达式(上面)求值并输出结果:

{"foo1": false, "foo2": true, "foo3": "foobar!"}

关于ruby - 如何解析抓取的 JSON 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8632696/

相关文章:

java - 我有一个字符串 (( Relationship=11 ) AND ( Relationship=12 ) AND ( Relationship=1 ))

java - 正则表达式 java 中的 4 个条件中的 3 个

ruby-on-rails - state_machine 对转换的验证

ruby-on-rails-3 - 博客集成到现有应用程序中

ruby-on-rails - rr gem assert_received 相当于 mocha gem

ruby - 在 Windows XP 中安装 Ruby Curb gem

ruby - some_method 的循环复杂度太高

ruby - 使用 watir-webdriver 打开多个线程导致 'Connection refused' 错误

java - 在java中为行之间存在的字符串编写正则表达式

ruby-on-rails - 使用 DataMapper get 在 Rails3 Controller 中处理 404 的最佳方法