首页 > 解决方案 > 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. 添加一个名为“contexts”的字段,其中包含 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

但是,我不知道该怎么做(2)。特别是,我很难理解 if/then/else/end 构造以及如何在分配中使用它,尤其是尝试使用它test()来检查文本“监视器”。

谁能指出我正确的方向?

标签: jsonjq

解决方案


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

推荐阅读