如果不存在,如何有条件地将密钥添加到json?

我有一个包含以下数据的json文件:

{
  "Index" : {
    "example_user" : {
      "important_key" : "leave_me_alone","blah" : {
        "more_stuff" : {
          "ignore_this" : "and_this_too"
        }
      }
    },"another_user" : {
      "blah" : {
        "more_stuff" : {
          "ignore_this" : "and_this_too"
        }
      }
    },"extra_person" : {
      "blah" : {
        "more_stuff" : {
          "ignore_this" : "and_this_too"
        }
      }
    }
  }
}

如您所见,important_keyanother_user中缺少extra_person

我的目标是有条件地在缺少的地方添加"imporant_key" : "",但 替换任何现有的 important_key值。我使用的程序是https://stedolan.github.io/jq/中的JQ(1.6)。

jqplay.org上多次尝试失败之后,并在互联网上进行了大量研究(重新)如何完成工作,我只能设法实现以下目标:

过滤器.Index[]+={"important_key":"data"}

结果

{
  "Index": {
    "example_user": {
      "important_key": "data","blah": {
        "more_stuff": {
          "ignore_this": "and_this_too"
        }
      }
    },"another_user": {
      "blah": {
        "more_stuff": {
          "ignore_this": "and_this_too"
        }
      },"important_key": "data"
    },"extra_person": {
      "blah": {
        "more_stuff": {
          "ignore_this": "and_this_too"
        }
      },"important_key": "data"
    }
  }
}

我知道+=(过度)会写入任何现有键值(请注意example_user)。我一直在尝试使用多个piped过滤器/运算符,包括|={ },但最后,上述结果是我能得到的最接近的结果。 / p>

(不幸的是,我似乎找不到所有东西都变得“疯狂”的jqplay代码片段)

wflwfl 回答:如果不存在,如何有条件地将密钥添加到json?

必须有条件地做某件事时,必须使用ifselect或其他方式进行某种过滤。

对于您要检查的每个对象,请检查该对象是否具有important_key,并在必要时添加它。如果它具有密钥,则什么也不做,否则进行设置。

.Index[] |= if has("important_key") then . else .important_key = $myImportantKey end
本文链接:https://www.f2er.com/3094825.html

大家都在问