【问题标题】:How can I add a variable to all items of an existing JSON array?如何将变量添加到现有 JSON 数组的所有项目?
【发布时间】:2025-12-23 08:00:11
【问题描述】:

我有以下来自 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"

【问题讨论】:

  • Yes 或 No 的值如何确定?也请张贴所做的尝试
  • 这能回答你的问题吗? Add new element to existing JSON array with jq
  • .[] |= . + {"critical": "No"}
  • 不幸的是“使用 jq 向现有 JSON 数组添加新元素”的问题是关于向数组添加项目,而不是向数组条目添加变量 yes 或 no 的值取决于它是哪个文件路径。所以在filepath1中,它应该是no,而在filepath 2中是yes,但是因为我只有五个可用的路径,我只想检查路径值是什么,如果它来自1、2、3、4或5,然后如果关键与否。
  • @puffel:你的说法好像矛盾,你说filepath1应该是no,但后来又说如果路径是1,2,3,4 or 5,那么关键是吗?

标签: json jq


【解决方案1】:

您可以使用jq if-statement

jq '.[] |= . + {"critical": (if .file == "FilePath1" or .file == "FilePath3" then "no" else "yes" end)}'

Try it on jqPlay

【讨论】:

【解决方案2】:

为了尽量减少冗余,您可以使用:

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

或者为了简洁:

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

【讨论】:

    最近更新 更多