【问题标题】:Flatten JSON with Jq with array index in output使用 Jq 展平 JSON,并在输出中使用数组索引
【发布时间】:2021-01-28 06:46:36
【问题描述】:

我正在尝试基于嵌套的 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
  }
]

我能够获取的唯一输出是在这个 sn-p 上:

https://jqplay.org/s/G6mYAI47LE

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

【问题讨论】:

    标签: json jq flatten


    【解决方案1】:

    Q.E.D.如下:

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

    这里简洁(或至少干燥)的关键是 jq 表达式 {$x} 扩展为 {"x": $x}。

    【讨论】:

      猜你喜欢
      • 2020-11-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-29
      相关资源
      最近更新 更多