【问题标题】:How to insert element into array with jq如何使用jq将元素插入数组
【发布时间】:2021-05-31 08:42:44
【问题描述】:

我有 JSON

[
  {"id": "1"},
  {"id": "5"},
  {"id": "9"},
  {"id": "0"},
  {"id": "3"}
]

我要插入一个对象来生产:

[
  {"id": "1"},
  {"id": "5"},
  {"id": "2"},
  {"id": "9"},
  {"id": "0"},
  {"id": "3"}
]

我该怎么做这个jq?通过索引或相对于其他对象。

编辑:这不是 Add new element to existing JSON array with jq 的副本,它是关于向数组添加/添加元素。如前所述,我想插入一个元素。

【问题讨论】:

标签: arrays json insert jq


【解决方案1】:

我不确定这是否是一个好的解决方案,但你去吧:

发件人:

[0, 1, 3]

收件人:

[0, 1, 2, 3]

与:

jq '[.[0:2][], 2, .[2:][]]' input.json
//   ^         ^  ^
//   A         B  C
  • A:第一个过滤器:所有项目之前新项目
  • B:第二个过滤器:您的新项目
  • C:第三个过滤器:新项目之后的所有项目

【讨论】:

    【解决方案2】:

    这里有两个将元素插入数组的定义:

    # Insert $x into the input array, such that after insertion,
    # if $i is in range(0;length+1), then .[$i] == $x
    def insert($i; $x): .[:$i] + [$x] + .[$i:];
    
    # Emit the zero-based index of $needle in the stream, s, but if s is empty, emit null:
    def index_of($needle; s):
     label $go
     | foreach s as $x (-1; .+1; select($x==$needle) | (., break $go)) // null;
    
    # Insert $x after the first occurrence of $needle in the input array,
    # but if $needle is not present, then append $x:
    def insert_after($needle; $x):
     index_of($needle; .[]) as $ix
     | if $ix then insert($ix + 1; $x) else . + [$x] end;
    

    【讨论】:

      猜你喜欢
      • 2017-12-13
      • 1970-01-01
      • 2012-07-11
      • 2021-08-14
      • 2012-11-09
      • 2017-11-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多