【问题标题】:how to add an element to a list only when it is not exists already if the list is null create one?如果列表为空,如何仅在元素不存在时才将元素添加到列表中创建一个?
【发布时间】:2018-05-12 01:49:08
【问题描述】:

输入

{
  "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
  • whatever3 aready 有 depb.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"]'

【问题讨论】:

    标签: arrays json jq


    【解决方案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")
    

    【讨论】:

      【解决方案2】:

      经过反复试验,看起来这是一种方法。

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

      【讨论】:

      • 这个解决方案可能是可以接受的,但它有几个缺点(它涉及“排序”)并且偏离规范(例如,考虑“未触及”的要求)。
      猜你喜欢
      • 1970-01-01
      • 2018-03-05
      • 1970-01-01
      • 2013-06-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-17
      • 1970-01-01
      相关资源
      最近更新 更多