1

How do we fetch the email from the entry whose level key has the value 2 from the below JSON document?

The expected output is

[email protected]

Any suggestion, please?

{
  "escalation_policy": {
    "on_call": [
      {
        "level": 2,
        "start": "2022-05-25T00:30:00Z",
        "end": "2022-05-25T09:30:00Z",
        "user": {
          "id": "ABOKC",
          "name": "Jaavena Dobey",
          "email": "[email protected]",
          "time_zone": "Tokyo"
        }
      },
      {
        "level": 7,
        "start": "2022-05-23T01:00:00Z",
        "end": "2022-05-30T01:00:00Z",
        "user": {
          "id": "KLSPSP",
          "name": "kosls frank",
          "email": "[email protected]",
          "time_zone": "Tokyo"
        }
      },
      {
        "level": 3,
        "start": "2022-05-23T01:00:00Z",
        "end": "2022-05-30T01:00:00Z",
        "user": {
          "id": "SKSPSLSL",
          "name": "Smitha Choudhary",
          "email": "[email protected]",
          "time_zone": "Tokyo"
        }
      }
    ]
  }
}

2 Answers 2

0

Like this,

  1. Get the array of the objects.
  2. Select the ones where level is 2
  3. Of the array returned, print the user's email

Invocation and output,

$ jq ".escalation_policy.on_call[] | select( .level == 2) | .user.email" test.json
"[email protected]"
0

The following gets one of the email addresses of the people on call, namely the first one with an escalation policy on call level equal of 2:

jq -r '.escalation_policy.on_call | map(select(.level == 2))[0].user.email' file

You didn't ask for this specifically, but the following gives you the email address of the on-call person with the lowest .level. We do this by sorting the on_call array and returning the .user.email value from the entry that sorts first:

jq -r '.escalation_policy.on_call | sort_by(.level)[0].user.email' file

We could also make sure that the current time is within the .start and .end timestamps. We do this by selecting only the relevant on-call entries before sorting them as before:

jq -r '
    .escalation_policy.on_call |
    map(select( now > (.start|fromdate) and now < (.end|fromdate) )) |
    sort_by(.level)[0].user.email' file

We can do this because we're lucky enough to have dates in exactly the format that the fromdate function in jq expects.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .