我需要获取存储在脚本标记中的函数中的 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/