在下面的JSON示例中,如何找到包含字符串“选择”的所有元素,并将它们替换为另一个字符串,例如“品位”。因此,在下面的所有字段中,名称“*选择”应改为“*年级”。
我把预期的产出贴在下面。考虑到我不知道有多少字段将有字符串“选择”,我不想简单地做[$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"
}
}
]
}
}发布于 2019-11-22 09:13:51
可能有更简单的方法,但这是我在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] |
)}, $$)
)但是,如果您不知道前面的前缀集,并且希望选择所有以“选择”结尾的属性名称,那么下面的表达式将得到这样的结果:
$prefixes := $keys(**)[$ ~> /Choice$/].$substringBefore('Choice')
我最后的表情。您可以在您的数据上进行在练习器里实验。
发布于 2021-11-18 10:36:51
我知道那是2019年,但这里有一个替代方案来帮助未来的读者。
$replace($string(),/([first|second|third])Choice/,"$1Grade")~>$eval()
https://stackoverflow.com/questions/58982136
复制相似问题