【问题标题】:Use jq to delete keys which match a listing in another JSON file使用 jq 删除与另一个 JSON 文件中的列表匹配的键
【发布时间】:2019-07-22 00:13:46
【问题描述】:

我有一个json文件A:

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

和一个json文件B:

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

}

我想删除文件 B 中与文件 A 的“删除”部分匹配的所有键。 问题是我不知道文件 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 来实现?感谢您的帮助!

【问题讨论】:

    标签: json key edit jq


    【解决方案1】:

    保持简单:

    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
    

    或者,如果您想要一个单行并且不喜欢已弃用的功能并且不介意not

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多