jq - 如何修改jq中数组的每个元素

标签 jq

假设我有一个 JSON:

[
    {
        "title": "Title1",
        "reference": [
            "123"
        ]
    },
    {
        "title": "Title2",
        "reference": [
            "234",
            "345"
        ]
    }
]

我想修改引用数组的每个元素,以便引用出现两次。我想要实现的目标:

[
    {
        "title": "Title1",
        "reference": [
            "123 is 123"
        ]
    },
    {
        "title": "Title2",
        "reference": [
            "234 is 234",
            "345 is 345"
        ]
    }
]

我已经尝试过:

jq '.[] | .reference = [("\(.reference[]) is \(.reference[])")]'

但是当数组有多个项目时,这会失败:

{
  "title": "Title1",
  "reference": [
    "123 is 123"
  ]
}
{
  "title": "Title2",
  "reference": [
    "234 is 234",
    "345 is 234",
    "234 is 345",
    "345 is 345"
  ]
}

如何修改上面的jq以达到预期的结果?

提前致谢!

最佳答案

map(.reference |= map(. + " is " + .))

将每个 .reference 更改为 .reference is .reference


[
  {
    "title": "Title1",
    "reference": [
      "123 is 123"
    ]
  },
  {
    "title": "Title2",
    "reference": [
      "234 is 234",
      "345 is 345"
    ]
  }
]

Demo

关于jq - 如何修改jq中数组的每个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75461609/

相关文章:

json - 如何使用 jq 获得每个组和子组的最大值

json - jq - 添加新字段并更新整个文件

shell - 需要帮助将对象数组减少为一个总和

json - 嵌套数组,使用 JQ 组合多个过滤器

bash - "Invalid numeric literal"使用 jq 和 openai api

json - 使用 JQ 从 JSON 中选择特定的、任意嵌套的对象

json - 在正确的部分添加 JSON 值

json - 如何使用 jq 将 JSON 转换为 CSV?

json - 用 jq 合并两个 JSON 对象

json - jq 1.5 - 更改现有元素或添加新元素(如果不存在)