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"
}

我想做两件事:

  1. 添加一个名为";上下文";包括account_id的值,例如:ex01.json
{
"account_id": "a01",
"contexts": [
"aws/a01"
],
"name": "example01",
"directory": "path/to/something"
}
  1. 如果"目录";包含文本";监视器";,我想在上下文中添加另一项,例如: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

然而,我不知道该怎么做。特别是,我很难理解if/then/else/end结构以及如何在赋值中使用它,尤其是试图将它与test()一起使用以检查文本";监视器";。

有人能给我指正确的方向吗?

一个简单的if/else子句就足够了。对于一个简单的布尔断言,可以使用test/matchcontains,然后相应地添加字段。

.contexts += [ "aws/" + .account_id ] |  
if   .directory | test("monitor") 
then .contexts  += [ "datadog/m01" ] else . end

最新更新