Adding/Appending 在 bash 脚本中通过 jq 对象到嵌套的 JSON 数组

Adding/Appending objects to a nested JSON array via jq in a bash script

这是我之前 post.

的后续

我已经能够在单个 JSON 数组上动态添加和追加对象。 但是,我在嵌套数组列表上尝试相同操作时遇到了困难。

可以通过海绵做到这一点:

{
  "profiles": [
    {
      "name": "Paul",
      "car": "Nissan",
      "colour": "Black"
    }
  ]
}

追加:

Enter name:
Joe
Enter Car Model:
BMW
Enter Colour:
Blue

Add a new entry? (y/n):  y
Enter name:  
Paul
Enter Car Model:  
Nissan
Enter Colour:  
Black

Add a new entry? (y/n):  n

{
  "profiles": [
    {
      "name": "Joe",
      "car": "BMW",
      "colour": "Blue"
    },
    {
      "name": "Paul",
      "car": "Nissan",
      "colour": "Black"
    }
  ]
}

我正在尝试做的是这样的:

{
  "key1": "One",
  "key2": "Two",
  "profiles": [
    {
      "name": "Joe",
      "car": "BMW",
      "colour": "Black"
    },
    {
      "name": "Sarah",
      "car": "Mercedes",
      "colour": "Red"
    }
  ],
  "key3": "Three",
  "list2": [
    "list2"
  ],
  "key4": "Four",
  "list3": [
    {
      "key5": "Five"
    }
  ]
}

基本上是想add/append对象到嵌套的profiles数组。

在我的问答和循环之后一直在使用以下内容:

jq --arg name "$name" --arg car "$car" --arg colour "$colour" ' .profiles += [{ $name, $car, $colour}] ' profiles.json | sponge profiles.json

然后将输出读取到要在我的最终 jq 命令中使用的变量:

profiles=`cat profiles.json`

然而,这个最终的jq没有正确输出。

jq -n --arg key1 "$key1" --arg key1 "$key2" --arg profiles "$profiles" --arg key3 "$key3" --arg key4 "key4" --arg key5 "key5" '{$key1, $key2, "profiles": $profiles, $key3, "list2": ["list2"], $key4, "list3": [{$key5}]}' > new_model.json

就算我改成:

"profiles": [.profiles],

给出空值:

{
  "key1": "One",
  "key2": "Two",
  "profiles": [
    null
  ],
  "key3": "Three",
  "list2": [
    "list2"
  ],
  "key4": "Four",
  "list3": [
    {
      "key5": Five
    }
  ]
}

考虑到其他键*值是动态添加的,不是固定的;有没有人知道我如何 add/append 或将 profiles.json 正确输入 nested profiles 数组?

最好排除 profiles.json 输出的开始和结束括号 {}。

{
  "profiles": [
    {
      "name": "Joe",
      "car": "BMW",
      "colour": "Black"
    },
    {
      "name": "Sarah",
      "car": "Mercedes",
      "colour": "Red"
    }
  ]
}

可能在每个问答块更新文件之后使用 jq 和 sponge(就像对单个数组所做的那样),删除 -n 标志等? 由于移动部件较多,并且配置文件数组嵌套在其他动态添加的键值中,因此对逻辑有点困惑。

非常感谢

存在其他键的事实不会使您在没有其他键时使用的策略无效。

据我所知,您的问题始于使用 bash 变量存储结果:

profiles=`cat profiles.json`

这本身当然是无害的(至少在文件足够小的情况下),但事情从那里开始走下坡路。例如,当你写:

 --arg profiles "$profiles" 

jq 变量 $profiles 现在包含一个 JSON 字符串,这不是您想要的。您可以使用 --argjson 将这只兔子追到它的兔子洞里,但目的是什么?