在输出中使用带有数组索引的Jq展平JSON

时间:2020-10-13 21:38:11

标签: json jq flatten

我正在尝试基于嵌套的Json创建单个json输出:

{
    "Id" : "1",
    "items" : [
        {"item_name" : "shirt","value" : 10},
        {"item_name" : "dress","value" : 20},
        {"item_name" : "ice cream","value" : 30}
    ] 
}

我的预期输出是:

[
  {
    "id": "1",
    "item_name": "shirt",
    "value": 10,
    "index_position": 0
  },
  {
    "id": "1",
    "item_name": "dress",
    "value": 20,
    "index_position": 1
  },
  {
    "id": "1",
    "item_name": "ice cream",
    "value": 30,
    "index_position": 2
  }
]

我能够提取的唯一输出是此代码段:

https://jqplay.org/s/G6mYAI47LE

迭代内部数组并同时获取外部对象数据的最佳方法是什么?

1 个答案:

答案 0 :(得分:1)

Q.E.D。如下:

.Id as $Id
| .items
| [ range(0; length) as $index_position
   | {$Id} + .[$index_position] + {$index_position} ]

此处简洁(或至少具有DRY风格)的关键在于jq表达式{$x}扩展为{"x": $x}