简体   繁体   English

使用 jq 删除与另一个 JSON 文件中的列表匹配的键

[英]Use jq to delete keys which match a listing in another JSON file

I have a json file A:我有一个json文件A:

{
  "remove" : ["foo", "bar"]
}

and a json file B:和一个json文件B:

{
    "someDynamicKey" : {
        "foo" : 1,
        "xyz" : 2,
        "bar" : "x"
     }

}

I want to remove all keys in file B that match in "remove" section in file A. The problem is that I don't know which keys would be in file A.我想删除文件 B 中与文件 A 中“删除”部分匹配的所有键。问题是我不知道文件 A 中将有哪些键。

Expect:预计:

{
    "someDynamicKey" : {
        "xyz" : 2
     }

}

I was trying我在尝试

jq --slurpfile a A.json '. as $b | reduce  $a[] as $key ($b; . = del($b.$key))'  B.json

and got error :并得到错误:

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)) 

I am not sure how to do next or is it possible to achieve using jq?我不确定下一步该怎么做,或者是否可以使用 jq 来实现? I appreciate any help!!我感谢任何帮助!

Keeping it simple:保持简单:

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

Or if you want a one-liner and don't like deprecated features and don't mind not :或者,如果你想要一个班轮和不喜欢建议使用的功能,不介意not

jq --slurpfile A A.json '$A[0].remove as $keys | .someDynamicKey |= with_entries(select( .key as $k | $keys | index($k) | not))' B.json

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM