Ruby 如何解析刮取的JSON字符串
我需要在脚本标记中获取存储在函数中的JSON字符串的值,如下所示:Ruby 如何解析刮取的JSON字符串,ruby,regex,ruby-on-rails-3,xpath,mechanize,Ruby,Regex,Ruby On Rails 3,Xpath,Mechanize,我需要在脚本标记中获取存储在函数中的JSON字符串的值,如下所示: <script type="text/javascript"> my.function("bar", {"foo1": false, "foo2": true, "foo3": "foobar!"}); </script> 但我不知道如何从那里继续下去。如何提取字符串的JSON部分并将其转换为哈希,以便提取值?如果表单没有更改,您可以这样做 JSON.parse(/\{.*\}/.match(t
<script type="text/javascript">
my.function("bar", {"foo1": false, "foo2": true, "foo3": "foobar!"});
</script>
但我不知道如何从那里继续下去。如何提取字符串的JSON部分并将其转换为哈希,以便提取值?如果表单没有更改,您可以这样做
JSON.parse(/\{.*\}/.match(txt)[0])
使用
json
gem。请注意,存在多个故障点-检查每个步骤,或者在某个地方放置一个漂亮的救援。这里是一个纯XPath 1.0解决方案:
concat('{',
substring-before(
substring-after(
substring-after(., 'my.function('),
'{'
),
');'
)
)
<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>
<script type="text/javascript">
my.function("bar", {"foo1": false, "foo2": true, "foo3": "foobar!"});
</script>
{"foo1": false, "foo2": true, "foo3": "foobar!"}
使用:
concat('{',
substring-before(
substring-after(
substring-after(., 'my.function('),
'{'
),
');'
)
)
<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>
<script type="text/javascript">
my.function("bar", {"foo1": false, "foo2": true, "foo3": "foobar!"});
</script>
{"foo1": false, "foo2": true, "foo3": "foobar!"}
基于XSLT的验证:
concat('{',
substring-before(
substring-after(
substring-after(., 'my.function('),
'{'
),
');'
)
)
<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>
<script type="text/javascript">
my.function("bar", {"foo1": false, "foo2": true, "foo3": "foobar!"});
</script>
{"foo1": false, "foo2": true, "foo3": "foobar!"}