如何解析刮JSON字符串
问题描述:
我需要抓住存储函数内的脚本标记像这样的JSON字符串的值:如何解析刮JSON字符串
<script type="text/javascript">
my.function("bar", {"foo1": false, "foo2": true, "foo3": "foobar!"});
</script>
我可以用机械化,像这样的特定标签:
parser.xpath("//script[ contains(text(), 'my.function')]").text
但我不知道该如何继续下去。我如何提取字符串的JSON部分并将其转换为散列,以便我可以提取这些值?
答
如果表单不会改变,你可以做
JSON.parse(/\{.*\}/.match(txt)[0])
与json
宝石。请注意,有几个故障点 - 检查每一步,或在某处放置一个不错的rescue
。
答
这里是一个纯的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!"}
+0
非常好。这比公认的解决方案更好。 – pguardiario 2011-12-26 09:15:34
正是我需要的,谢谢! – David 2011-12-26 04:12:53