1

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 Answers1

2

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
Inian
  • 80,270
  • 14
  • 142
  • 161
  • 1
    Ah, I was omitting the "else" branch, which `jq` doesn't seem to like, even thought it says it does here: https://stedolan.github.io/jq/manual/#ConditionalsandComparisons This does not work: ``` jq '.contexts += ["aws/" + .account_id] | if .directory | test("monitor") then .contexts += ["datadog/td01"] end' ex01.json ``` I get: ``` jq: error: syntax error, unexpected end (Unix shell quoting issues?) at , line 1: .contexts += ["aws/" + .account_id] | if .directory | test("monitor") then .contexts += ["datadog/td01"] end ``` – Robin Bowes Jul 14 '21 at 14:39
  • Your hyperlink is for the “development” version of jq. For any particular version of jq other than “master”, it’s best to use the corresponding version of the manual. Links are provided at the top. – peak Jul 14 '21 at 18:12
  • I could have sworn I read somewhere that this feature was introduced in 1.6, but after re-visiting, I see it says "after the release of jq 1.6". It was indeed you, @peak, here: https://stackoverflow.com/a/29962258/2339410 :) – Robin Bowes Jul 15 '21 at 12:11