根据条件将密钥批量添加到目录中的 JSON 个文件中

Batch add keys into JSON files in a directory based on condition

我正在寻找一种方法,最好使用命令行工具将密钥批量添加到目录中的所有 JSON 文件。

文件:

/config$ ls
166bbdd41c0297755ddb645db2b4c865  46a5c83d30483acba49a542a1ade9c33  87b2a640a5398156bf2d924b130ce42c  ca5b4cbc16a580cf5236097ec39e90e9

JSON结构为:

{
        "enabled": true,
        "services": [
                "933579ee8caafc4e818ddfe02ab58fdc"
        ],
        "tags": [
                "2a521880b86a0f043eb65cff37fac679",
                "b4fd044b9a7ab1146bb638ea42219b99"
        ],
        "bouquet": ""
}

问题是,如果文件的“tags”数组中包含“b4fd044b9a7ab1146bb638ea42219b99”值,那么向数组“services”添加新元素的最佳方式是什么。如果“tags”数组中不存在该值,则跳过该文件,否则将“NEWVALUETOADD”添加到“services”。

如果“NEWVALUETOADD”已经存在,我们也可以跳过该文件。

示例输出:

{
        "enabled": true,
        "services": [
                "NEWVALUETOADD"
                "933579ee8caafc4e818ddfe02ab58fdc"
        ],
        "tags": [
                "2a521880b86a0f043eb65cff37fac679",
                "b4fd044b9a7ab1146bb638ea42219b99"
        ],
        "bouquet": ""
}

一个简单的 if … then … else … end 可能会:

jq --arg q "b4fd044b9a7ab1146bb638ea42219b99" --arg n "NEWVALUETOADD" '
  if IN(.tags[]; $q) and (IN(.services[]; $n) | not)
  then .services += [$n] else . end
'
{
  "enabled": true,
  "services": [
    "933579ee8caafc4e818ddfe02ab58fdc",
    "NEWVALUETOADD"
  ],
  "tags": [
    "2a521880b86a0f043eb65cff37fac679",
    "b4fd044b9a7ab1146bb638ea42219b99"
  ],
  "bouquet": ""
}

Demo

为了遍历每个文件并修改它,您需要使用临时文件,因为 jq 没有就地编辑选项(因为 sedsed -i 有)。

for file in *
do jq --arg q "b4fd044b9a7ab1146bb638ea42219b99" --arg n "NEWVALUETOADD" '
    if IN(.tags[]; $q) and (IN(.services[]; $n) | not)
    then .services += [$n] else . end
  ' "$file" > "$file.new" && mv "$file.new" "$file"
done

这样:

jq --arg nv "NEWVALUETOADD" 'select(.tags[] | select(. == "b4fd044b9a7ab1146bb638ea42219b99") ).services += [$nv]'

jq 脚本:

select(
  .tags[] | select(
    . == "b4fd044b9a7ab1146bb638ea42219b99"
  )
).services += [$nv]

jqplay.org with this above

一个选项是使用索引来找到与所需值的精确匹配,然后添加新元素,例如

jq '(select(.tags | index("b4fd044b9a7ab1146bb638ea42219b99")).services )+=["New Value"]' yourfile  

Demo