【问题标题】:Updating Nested JSON Array with new key and value from another key使用来自另一个键的新键和值更新嵌套 JSON 数组
【发布时间】:2021-11-12 10:55:15
【问题描述】:

我有一个 JSON 文件,其中有任务 ID。有些任务可以是空的。我想把ID放到task不为空的task中。

[
  {
    "id": 1961126,
    "tasks": [
      {
        "id": 70340700,
        "title": "Test1",
      },
      {
        "id": 69801130,
        "title": "Test15A",
      }
    ]
  },
  {
    "id": 1961126,
    "tasks": []
  }           
]  

我想让任务数组更新为如下所示

[
  {
    "id": 1961126,
    "tasks": [
      {
        **"sId":1961126,**
        "id": 70340700,
        "title": "Test1",
      },
      {
        **"sId":1961126,**
        "id": 69801130,
        "title": "Test15A",
      }
    ]
  },
  {
    "id": 1961126,
    "tasks": []
  }           
] 

我不知道如何从对象中获取 id 到嵌套数组中。这是我想出来的

jq 'map(.tasks[0]|select( . != null )|.sId = .id)' file.json

这只是拉入相同的ID。我已经厌倦了输入[].id 但我收到错误Cannot index number with string "id". 我仍在学习如何处理嵌套数组和对象。

【问题讨论】:

    标签: json jq


    【解决方案1】:

    将 ID 保存在变量中,并将其作为新字段添加到每个数组成员。

     jq 'map(.id as $sId | .tasks[] += {$sId})' file.json
    

    Demo

    注意 #1:去掉每个对象中最后的 ,(参见演示),因为它不是正确的 JSON。

    注意 #2:对象字段通常没有顺序,但如果您希望首先显示传播的 ID,如预期的输出所示,您可以尝试替换 += {$sId}(它本身是 @987654326 的简写@) 与 |= {$sId} + . 翻转生成顺序 (Demo)。虽然不能保证它在进一步处理时保持这种状态。

    【讨论】:

    • 这行得通。也感谢您的笔记。我确实得到了 a 但我通过添加一个 ?在 .tasks[] 之后。就像这样 jq 'map(.id as $sId | .tasks[]? += {$sId})' file.json
    • 这意味着tasks 可能确实是null 甚至丢失,而不仅仅是[](一个空数组),如您的示例中提供的那样。使用? 实际上是处理这些情况的正确方法。
    猜你喜欢
    • 1970-01-01
    • 2022-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-27
    • 2016-07-27
    • 2018-11-04
    • 2021-10-13
    相关资源
    最近更新 更多