我正在尝试一种 JSON 模板机制。
我有这个简化的示例 JSON 模板
{
"type": "AdaptiveCard",
"body": [
{
"type": "Container",
"isVisible": "$._has_content.success",
"items": [
{
"type": "TextBlock",
"text": "$.result[0].text",
},
{
"type": "FactSet",
"facts": [
"$.success.*"
]
}
]
},
{
"type": "Container",
"style": "attention",
"isVisible": "$._has_content.fail",
"items": [
{
"type": "TextBlock",
"text": "Failures",
},
{
"type": "FactSet",
"facts": [
"$.fail.*"
]
}
]
}
],
}
我现在需要过滤所有值以“$”开头的节点。
所以应该找到这些:
$.body[0].isVisible
$.body[0].items[0].text
$.body[0].items[1].facts
$.body[1].isVisible
$.body[1].items[1].facts
我刚刚开始使用 JSON Path,还没有找到定义适当过滤器的方法。
我的尝试如
$.body..*[?(@.* =~ /^\$./)]
失败了。
并非所有 JSON Path 实现都支持正则表达式,但是官方 JSON Path 规范(刚刚发布!)确实定义了
match()
(隐式锚点)和 search()
(显式锚点)正则表达式处理。
由于这是新发布的规范,因此可能还没有很多实现符合。但是,我的可以,您可以在 https://json-everything.net/json-path 上使用它。
因此,如果您使用
$.body..*[?search(@, '^\\$.*')]
,您将得到您正在寻找的结果:
[
{
"Value": "$._has_content.success",
"Location": "$['body'][0]['isVisible']"
},
{
"Value": "$._has_content.fail",
"Location": "$['body'][1]['isVisible']"
},
{
"Value": "$.result[0].text",
"Location": "$['body'][0]['items'][0]['text']"
},
{
"Value": "$.success.*",
"Location": "$['body'][0]['items'][1]['facts'][0]"
},
{
"Value": "$.fail.*",
"Location": "$['body'][1]['items'][1]['facts'][0]"
}
]
其中包括每个节点的值和位置。
请注意,转义
\
需要加倍,因为它是字符串文字(JSON 转义规则)。
我建议联系实施维护者,看看他们的库支持什么。