json - 如何将变量添加到现有 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"
解决方案
为了最大限度地减少冗余,您可以使用:
map(. + {critical: (if .file | IN("FilePath1", "FilePath3") then "no" else "yes" end) })
或为简洁起见:
map(. + {critical: ((.file | select(IN("FilePath1", "FilePath3")) | "no") // "yes" )})
推荐阅读
- javascript - 如何从浏览器打开windows应用程序
- javascript - MongoDB 查询聚合 localField ObjectId 字符串和外部字段 ObjectId
- android - 对象 CountDownTimer 的全局变量
- asp.net - 我的 .js 文件 (jquery) 的源 (src) 标记正在我的 Web 应用程序上自动修改
- java - 线程“main”中的异常 java.lang.reflect.InvocationTargetException -> 原因:java.lang.NoClassDefFoundError: BOOT-INF
- android - Android:如何从小米手环 4 获取健身数据?
- aws-api-gateway - Github Webhook 到与 SQS 集成的 AWS API Gateway 错误?
- javascript - 从 GTM 自定义 JS 变量中的 URL 返回文本
- google-sheets - 应用 VlLOOKUP 直到谷歌表格中的最后一个非空行
- c - 在程序中,扩大了形状的大小是成功的,但是改变颜色效果不好