在下面的JSON示例中,如何查找包含字符串“ Choice”的所有元素并将其替换为另一个字符串,例如“ Grade”。 因此,在所有字段下方,名称“ *** Choice”应更改为“ *** Grade”。
我在下面粘贴了预期的输出。鉴于我不知道多少个字段将包含字符串“ Choice”,因此我不想简单地进行[$in ~> | ** [firstChoice] | {"firstGrade": firstChoice}, ["firstChoice"] | ;]
的直接查找和替换。
{
"data": {
"resourceType": "Bundle",
"id": "e919c820-71b9-4e4b-a1c8-c2fef62ea911",
"firstChoice": "xxx",
"type": "collection",
"entry": [
{
"resource": {
"resourceType": "Condition",
"id": "SMART-Condition-342",
"code": {
"coding": [
{
"system": "http://snomed.info/sct",
"code": "38341003",
"display": "Essential hypertension",
"firstChoice": "xxx"
}
],
"text": "Essential hypertension"
},
"clinicalStatus": "active",
"secondChoice": "xxx"
},
"search": {
"mode": "match"
}
}
]
}
}
预期产量
{
"data": {
"resourceType": "Bundle",
"id": "e919c820-71b9-4e4b-a1c8-c2fef62ea911",
"firstGrade": "xxx",
"type": "collection",
"entry": [
{
"resource": {
"resourceType": "Condition",
"id": "SMART-Condition-342",
"code": {
"coding": [
{
"system": "http://snomed.info/sct",
"code": "38341003",
"display": "Essential hypertension",
"firstGrade": "xxx"
}
],
"text": "Essential hypertension"
},
"clinicalStatus": "active",
"secondGrade": "xxx"
},
"search": {
"mode": "match"
}
}
]
}
}
答案 0 :(得分:0)
可能有更简单的方法,但这是我在JSONata中想到的一个表达式:
(
$prefixes := $keys(**)[$ ~> /Choice$/].$substringBefore('Choice');
$reduce($prefixes, function($acc, $prefix) {(
$choice := $prefix & "Choice";
$acc ~> | ** [$lookup($choice)] | {$prefix & "Grade": $lookup($choice)}, [$choice] |
)}, $$)
)
它看起来很糟糕,但是我将解释如何构建它。
您从表达式开始
$ ~> | ** [firstChoice] | {"firstGrade": firstChoice}, ["firstChoice"] |
如果只想替换一个选项,并且知道全名,这很好。如果要替换多个,则可以将它们链接在一起,如下所示:
$ ~> | ** [firstChoice] | {"firstGrade": firstChoice}, ["firstChoice"] |
~> | ** [secondChoice] | {"secondGrade": secondChoice}, ["secondChoice"] |
~> | ** [thirdChoice] | {"thirdGrade": thirdChoice}, ["thirdChoice"] |
这时,您可以创建一个带有选择前缀并返回部分替换的高阶函数(请注意,|...|...|
语法会生成一个函数)。然后,您可以使用内置的$reduce()
高阶函数将它们链接在一起以获得一个前缀数组。这样您会得到如下内容:
(
$prefixes := ["first", "second", "third"];
$reduce($prefixes, function($acc, $prefix) {(
$choice := $prefix & "Choice";
$acc ~> | ** [$lookup($choice)] | {$prefix & "Grade": $lookup($choice)}, [$choice] |
)}, $$)
)
但是,如果您不预先知道前缀集,并且想选择所有以“ Choice”结尾的属性名称,则以下表达式将为您提供:
$prefixes := $keys(**)[$ ~> /Choice$/].$substringBefore('Choice')
然后到达我的最终表达。您可以在数据上here in the exerciser对其进行试验。