如何为数组中的嵌套数组中的多个对象生成连续索引

时间:2017-03-09 13:46:21

标签: json jq unique-id

鉴于

[{
  "objects": [{
    "key": "value"
  },{
    "key": "value"
  }]
}, {
  "objects": [{
    "key": "value"
  }, {
    "key": "value"
  }]
}]

如何生成

[{
  "objects": [{
    "id": 0,
    "key": "value"
  },{
    "id": 1,
    "key": "value"
  }]
}, {
  "objects": [{
    "id": 2,
    "key": "value"
  }, {
    "id": 3,
    "key": "value"
  }]
}]

使用jq?

我尝试使用这个,但id都是0

jq '[(-1) as $i | .[] | {objects: [.objects[] | {id: ($i + 1 as $i | $i), key}]}]'

2 个答案:

答案 0 :(得分:1)

这里一个简单解决方案的关键是将问题分解为简单的部分。这可以通过定义辅助函数addId/1来完成。一旦完成,剩下的就很简单了:

# starting at start, add {id: ID} to each object in the input array 
def addId(start):
  reduce .[] as $o
    ([];
     length as $l 
     | .[length] = ($o | (.id = start + $l)));

reduce .[] as $o
  ( {start: -1, answer: []};
    (.start + 1) as $next
    | .answer += [$o | (.objects |= addId($next))]
    | .start += ($o.objects | length) )
| .answer

答案 1 :(得分:0)

受到@peak回答的启发,我想出了这个解决方案。没有太大区别,只是生成ID并选择foreach而不是reduce的更短方式,因为涉及到中间结果。

def addIdsStartWith($start):
    [to_entries | map((.value.id = .key + $start) | .value)];

[foreach .[] as $set (
    {start: 0};
    .set = $set |
        .start as $start | .set.objects |= addIdsStartWith($start) |
        .start += ($set.objects | length);
    .set
)]