简体   繁体   English

使用jq有条件地将元素添加到json数组

[英]Conditionally add element to json array using jq

I'm adding strings to a JSON array using jq, and it works great, but I'd like to only add strings that do not already exist. 我正在使用jq将字符串添加到JSON数组,并且它工作得很好,但我只想添加尚不存在的字符串。 I've experimented with unique, has, not, etc. I'm missing a piece or two to the puzzle. 我已经尝试过独特的,有,而不是等等。我错过了一两块拼图。

Here's my starting json file, foo.json: 这是我的起始json文件foo.json:

{
  "widgets": [
    {
      "name": "foo",
      "properties": [
        "baz"
      ]
    },
    {
      "name": "bar"
    }
  ]
}

Here's the jq command I've constructed that adds the string, even if it already exists: 这是我构建的jq命令,它添加了字符串,即使它已经存在:

$ cat foo.json | jq '.widgets[] | select(.name=="foo").properties |= .+ ["cat"]'

Here's the latest iteration of my attempt. 这是我尝试的最新版本。

$ cat foo.json | jq '.widgets[] | select(.name=="foo").properties | has("cat") | not | .properties += ["cat"]'
jq: error: Cannot check whether array has a string key

There are many ways to do this. 有很多方法可以做到这一点。

Assuming elements of the array are supposed to be unique, which your use case strongly implies, you can just pass the resulting array after the addition through the unique filter. 假设数组的元素应该是唯一的,您的用例强烈暗示,您可以通过unique过滤器在添加后传递结果数组。

$ cat foo.json | jq '.widgets[] | select(.name=="foo").properties |= (.+ ["cat"] | unique)'

There's more than one way to skin a cat, as they say, but perhaps this will give you some ideas: 正如他们所说,有一种方法可以给猫皮肤,但也许这会给你一些想法:

.widgets[]
| select(.name=="foo")
| select(.properties | index("cat") | not)
| .properties += ["cat"]

With your input, the result is: 根据您的输入,结果是:

{
  "name": "foo",
  "properties": [
    "baz",
    "cat"
  ]
}

The following may be closer to what you're looking for: 以下内容可能更接近您的要求:

.widgets |= [ .[] | if .properties|index("cat")|not
                    then .properties += ["cat"]
                    else .
                    end]

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

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