jq conditionally add a new property based on value of another

Viewed 583

I jave a bunch of definitions in json format, and I'd like to process them to add a new field to a json map based on the value of another field outside the map.

Example data:

ex01.json:

{
  "account_id": "a01",
  "name": "example01",
  "directory": "path/to/something"
}

ex02.json:

{
  "account_id": "a01",
  "name": "example02",
  "directory": "path/to/monitors"
}

I want to do two things:

  1. add a field named "contexts" that includes the value of the account_id, eg: ex01.json
{
  "account_id": "a01",
  "contexts": [
    "aws/a01"
  ],
  "name": "example01",
  "directory": "path/to/something"
}
  1. If "directory" contains the text "monitors", I'd like to add another item to contexts, eg: ex02.json:
{
  "account_id": "a01",
  "contexts": [
    "aws/a01",
    "datadog/m01"
  ],
  "name": "example02",
  "directory": "path/to/monitors"
}

For (1), I can set the contexts field from the account_id like this:

jq '.contexts += ["aws/" + .account_id]' ex02.json

However, I can't figure out how to do (2). In particular, I'm struggling to understand the if/then/else/end construct and how to use it in assignment, especially trying to use it with test() to check for the text "monitors".

Can anyone point me in the right direction?

1 Answers

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
Related