如果列表为空,如何将元素添加到列表中时,如何创建一个元素?

时间:2018-05-12 01:49:09

标签: arrays json jq

输入

{
  "apps": [
    {
      "name": "whatever1",
      "id": "ID1"
    },
    {
      "name": "whatever2",
      "id": "ID2",
      "dep": [
        "a.jar"
      ]
    },
    {
      "name": "whatever3",
      "id": "ID3",
      "dep": [
        "a.jar",
        "b.jar"
      ]
    }
  ]
}

输出

{
  "apps": [
    {
      "name": "whatever1",
      "id": "ID1",
      "dep": [
        "b.jar"
      ]
    },
    {
      "name": "whatever2",
      "id": "ID2",
      "dep": [
        "a.jar",
        "b.jar"
      ]
    },
    {
      "name": "whatever3",
      "id": "ID3",
      "dep": [
        "a.jar",
        "b.jar"
      ]
    }
  ]
}

在上面的例子中

  • whatever1没有dep,因此请创建一个。
  • whatever2dep且没有b.jar,因此请添加b.jar
  • whatever3dep b.jar而且 # add blindly, whatever3 is not right cat dep.json | jq '.apps[].dep += ["b.jar"]' # missed one level and whatever3 is gone. cat dep.json | jq '.apps | map(select(.dep == null or (.dep | contains(["b.jar"]) | not)))[] | .dep += ["b.jar"]' 未受影响。

我的尝试。

{{1}}

2 个答案:

答案 0 :(得分:1)

为了清楚起见,让我们定义一个辅助函数来执行核心任务:

# It is assumed that the input is an object
# that either does not have the specified key or
# that it is array-valued
def ensure_has($key; $value):
  if has($key) and (.[$key] | index($value)) then .
  else .[$key] += [$value]
  end ;

现在可以直接完成任务:

.apps |= map(ensure_has("dep"; "b.jar"))

或者......

.apps[] |= ensure_has("dep"; "b.jar")

答案 1 :(得分:0)

经过一些试验和错误后,看起来这是一种方法。

cat dep.json | jq '.apps[].dep |= (. + ["b.jar"] | unique)'