Michael B
Michael B

Reputation: 12228

jq - How to get an alternative key if null

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'

Upvotes: 2

Views: 5285

Answers (3)

Eldar
Eldar

Reputation: 10790

 cat $JSON | jq -r 'map(if (.mail == null or .mail == "null")  then .userPrincipalName else .mail end)'

Since you asked it for bash jq method remains the same. we map the values of array check if mail == "null" if true use other property else use itself.

Here is the jq play link

Upvotes: 8

dropyourcoffee
dropyourcoffee

Reputation: 348

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

Upvotes: 3

Sunny Parekh
Sunny Parekh

Reputation: 983

I think you are trying to do something as mentioned below:

var newArray = [];
arr.forEach((obj) => {
    if (obj.mail !== 'null') {
        newArray.push(obj.mail);
    } else {
        newArray.push(obj.userPrincipalName);
    }});
console.log(newArray);   // ["user1.example.com","user2.example.com","user3.example.com"]

Upvotes: 0

Related Questions