【问题标题】:How to parse a scraped JSON string如何解析抓取的 JSON 字符串
【发布时间】:2011-12-26 03:09:04
【问题描述】:

我需要获取一个 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 部分并将其转换为哈希,以便提取值?

【问题讨论】:

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


    【解决方案1】:

    这是一个纯 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!"}
    

    【讨论】:

      【解决方案2】:

      如果表格没有改变,你可以这样做

      JSON.parse(/\{.*\}/.match(txt)[0])
      

      json 宝石。请注意,有几个失败点 - 要么检查每个步骤,要么在某处放置一个漂亮的rescue

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多