首页 > 解决方案 > 如何将变量添加到现有 JSON 数组的所有项目?

问题描述

我有来自 json 文件的以下 JSON 数组:

[
  {
    "key": "Ley1",
    "file": "Filepath1",
    "line": 10,
    "rule": "csharpsquid:S1643",
    "message": "Use a StringBuilder instead.",
    "type": "CODE_SMELL"
  },
  {
    "key": "Key2",
    "file": "FilePath2",
    "line": 12,
    "rule": "csharpsquid:S1643",
    "message": "Use a StringBuilder instead.",
    "type": "CODE_SMELL"
  }
]

我想使用 bash 命令将变量“critical”添加到它的所有项目中,所以它看起来像这样:

[
      {
        "key": "Key1",
        "file": "Filepath1",
        "line": 10,
        "rule": "csharpsquid:S1643",
        "message": "Use a StringBuilder instead.",
        "type": "CODE_SMELL",
        "critical": "No"
      },
      {
        "key": "Key2",
        "file": "FilePath2",
        "line": 12,
        "rule": "csharpsquid:S1643",
        "message": "Use a StringBuilder instead.",
        "type": "CODE_SMELL",
        "critical": "Yes"
      }
    ]

不幸的是,我是一个完整的 JSON 和 bash 初学者,找不到解决这个问题的 bash 命令。我在 jq-play 上用 jq 尝试了一点点,但并没有真正导致什么结果,所以我想在这里尝试一下。我希望这些都是需要的信息,所以有人知道可能有这个命令吗?

编辑:这在这里工作,谢谢!

.[] |= . + {"critical": "No"}

但是不,我想根据文件值确定“是”或“否”的值。您知道如何编辑命令以便检查文件值以确定临界值吗?

它应该这样决定:

Filepath1、Filepath3 导致"critical" : "No"

Filepath2、Filepath4、Filepath5 导致"critical" : "Yes"

标签: jsonjq

解决方案


为了最大限度地减少冗余,您可以使用:

map(. + {critical: (if .file | IN("FilePath1", "FilePath3") then "no" else "yes" end) })

或为简洁起见:

map(. + {critical: ((.file | select(IN("FilePath1", "FilePath3")) | "no") // "yes" )})

推荐阅读