jq递归更新某些元素的值 [英] jq recursively update values for certain elements
问题描述
以下JSON数据的目的是在type
t
的所有元素中使用src
的值更新字段dst
的值,而不管树中的深度如何,同时保留数据的整体结构.
The intent for the JSON data below is to update the value of the field dst
with the value of src
within all elements of type
t
, regardless of depth within the tree, while at the same time preserving the whole structure of the data.
使用jq
可以吗?我的几次尝试都归结为以下无法实现预期目的的命令:
Is this possible with jq
? My several attempts have boiled down to the following command that is not working to achieve the intended purpose:
$ jq -r 'map_values(select(.. | .type? == "t" |= (.dst = .src)))'
{
"a": "b",
"c": [
{
"type": "t",
"src": "xx",
"dst": "zz"
},
{
"type": "t",
"src": "xx",
"dst": "zz"
}
],
"d": [
{
"e": [
{
"type": "t",
"src": "xx",
"dst": "zz"
}
]
},
{
"type": "t2",
"src": "xx",
"dst": "zz"
}
]
}
推荐答案
jq有可能吗?
Is this possible with jq?
jq是图灵完成的:-)
jq is Turing-complete :-)
这是一个简单的解决方案:
Here's a simple solution:
walk( if type == "object" and .type == "t" then .dst = .src else . end)
如果您的jq没有walk/1
,则可能是升级(升级到jq 1.6)的好时机;否则,您可以从网络上获取其定义,例如通过谷歌搜索:jq "def walk"
If your jq does not have walk/1
, then it might be a good time to upgrade (to jq 1.6); otherwise, you can snarf its def from the web, e.g. by googling: jq "def walk"
reduce paths as $x (.;
if (getpath($x)|.type? // false) == "t"
then setpath( $x + ["dst"]; getpath( $x + ["src"] ))
else . end)
这篇关于jq递归更新某些元素的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!