使用 jq 删除与另一个 JSON 文件中的列表匹配的键
Use jq to delete keys which match a listing in another JSON file
我有一个 json 文件 A:
{
"remove" : ["foo", "bar"]
}
和一个 json 文件 B:
{
"someDynamicKey" : {
"foo" : 1,
"xyz" : 2,
"bar" : "x"
}
}
我想删除文件 B 中与文件 A 的 "remove" 部分匹配的所有密钥。
问题是我不知道哪些键会在文件 A 中。
预计:
{
"someDynamicKey" : {
"xyz" : 2
}
}
我在尝试
jq --slurpfile a A.json '. as $b | reduce $a[] as $key ($b; . = del($b.$key))' B.json
出现错误:
jq: error: syntax error, unexpected '$', expecting FORMAT or QQSTRING_START (Unix shell quoting issues?) at <top-level>, line 1:
. as $b | reduce $a[] as $key ($b; . = del($b.$key))
我不确定下一步该怎么做,或者是否可以使用 jq 实现?感谢您的帮助!!
保持简单:
jq --argfile A A.json '
$A.remove as $keys
| .someDynamicKey
|= with_entries( .key as $k
| if $keys | index($k)
then empty
else . end)' B.json
或者如果您想要 one-liner 并且不喜欢已弃用的功能并且不介意 not
:
jq --slurpfile A A.json '$A[0].remove as $keys | .someDynamicKey |= with_entries(select( .key as $k | $keys | index($k) | not))' B.json
我有一个 json 文件 A:
{
"remove" : ["foo", "bar"]
}
和一个 json 文件 B:
{
"someDynamicKey" : {
"foo" : 1,
"xyz" : 2,
"bar" : "x"
}
}
我想删除文件 B 中与文件 A 的 "remove" 部分匹配的所有密钥。 问题是我不知道哪些键会在文件 A 中。
预计:
{
"someDynamicKey" : {
"xyz" : 2
}
}
我在尝试
jq --slurpfile a A.json '. as $b | reduce $a[] as $key ($b; . = del($b.$key))' B.json
出现错误:
jq: error: syntax error, unexpected '$', expecting FORMAT or QQSTRING_START (Unix shell quoting issues?) at <top-level>, line 1:
. as $b | reduce $a[] as $key ($b; . = del($b.$key))
我不确定下一步该怎么做,或者是否可以使用 jq 实现?感谢您的帮助!!
保持简单:
jq --argfile A A.json '
$A.remove as $keys
| .someDynamicKey
|= with_entries( .key as $k
| if $keys | index($k)
then empty
else . end)' B.json
或者如果您想要 one-liner 并且不喜欢已弃用的功能并且不介意 not
:
jq --slurpfile A A.json '$A[0].remove as $keys | .someDynamicKey |= with_entries(select( .key as $k | $keys | index($k) | not))' B.json