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