json - jq 根据另一个值有条件地添加一个新属性
问题描述
我有一堆 json 格式的定义,我想处理它们以根据地图外另一个字段的值向 json 地图添加一个新字段。
示例数据:
ex01.json:
{
"account_id": "a01",
"name": "example01",
"directory": "path/to/something"
}
ex02.json:
{
"account_id": "a01",
"name": "example02",
"directory": "path/to/monitors"
}
我想做两件事:
- 添加一个名为“contexts”的字段,其中包含 account_id 的值,例如:ex01.json
{
"account_id": "a01",
"contexts": [
"aws/a01"
],
"name": "example01",
"directory": "path/to/something"
}
- 如果“目录”包含文本“监视器”,我想在上下文中添加另一个项目,例如:ex02.json:
{
"account_id": "a01",
"contexts": [
"aws/a01",
"datadog/m01"
],
"name": "example02",
"directory": "path/to/monitors"
}
对于 (1),我可以像这样从 account_id 设置 contexts 字段:
jq '.contexts += ["aws/" + .account_id]' ex02.json
但是,我不知道该怎么做(2)。特别是,我很难理解 if/then/else/end 构造以及如何在分配中使用它,尤其是尝试使用它test()
来检查文本“监视器”。
谁能指出我正确的方向?
解决方案
A simple if
/else
clause like below would suffice. For a simple boolean assertion, you could use test
/match
or contains
and then add the field accordingly.
.contexts += [ "aws/" + .account_id ] |
if .directory | test("monitor")
then .contexts += [ "datadog/m01" ] else . end
推荐阅读
- c# - Net Core:没有从“实体”到“IEntity”的隐式引用转换
- uialertview - 警告:尝试呈现
其视图不在窗口层次结构中 - python - 包含空格的属性的 XPath
- c++ - 尝试在 SET_VECTOR_ELT 中设置索引 0/0
- r - 单元测试 R Shiny App rhandsontable 与 shinytest
- java - Swift 的 CharacterSet.decimalDigits 和 unicodeScalars 的 Kotlin 等价物是什么?
- c# - 如何对 Serilog 的 LogContext 属性进行单元测试
- android - 基于 Google 应用中的 Material Design 2 自定义选择的标签指示器
- ibm-mq - 应用程序团队获取 JMSFMQ6312:Java(tm) MQI 中发生异常
- excel - 搜索宏未返回所有结果