Saturday, July 23, 2022

[SOLVED] jq - How to get an alternative key if null

Issue

given the following json -

[
  {
    "mail": "[email protected]",
    "userPrincipalName": "[email protected]"
  },
  {
    "mail": "[email protected]",
    "userPrincipalName": "[email protected]"
  },
  {
    "mail": "null",
    "userPrincipalName": "[email protected]"
  }
]

I want to get

[email protected]
[email protected]
[email protected]

I want to get all of the .com addresses. So I'm trying to write an if/then to check for mail being null. and if so get userPrincipleName instead.

Edit -

Apologies - I forgot to add, I'm running this in a bash script

cat $JSON | jq -r '.[].mail // .[].userPrincipalName'


Solution

Try this:

jq '.[]|if .mail | contains("null") then .userPrincipalName else .mail end' $JSON

Edition:

jq '.[]|if (.mail == null or .mail == "null") then .userPrincipalName else .mail end' $JSON



Answered By - dropyourcoffee
Answer Checked By - Senaida (WPSolving Volunteer)