mark
mark

Reputation: 62732

How to extract two attribute values from a json output and assign each of them to a dedicated variable in bash?

Please, observe:

~$ az ad sp show --id $spn_id --query '[appId, displayName]'
[
  "c...1",
  "xyz"
]

~$

I would like to assign each returned value to its own bash variable, namely to APP_ID and APP_DISPLAY_NAME respectively. My current solution is this:

~$ x=(`az ad sp show --id $spn_id --query '[appId, displayName]' -o tsv | tr -d '\r'`)

~$ APP_ID=${x[0]}

~$ APP_DISPLAY_NAME=${x[1]}

~$

Which works fine:

~$ echo $APP_ID
c...1

~$ echo $APP_DISPLAY_NAME
xyz

~$

I am curious if it is possible to do it in a more concise way?

Upvotes: 0

Views: 38

Answers (2)

Rajat Jain
Rajat Jain

Reputation: 2022

You can use the following with sed and xargs:

export $( az ad sp show --id $spn_id --query '[appId, displayName]' | tr -d "\n" | sed -E  "s/\[\s+(.+)\,\s+(.+)\]/APP_ID=\"\1\" \nAPP_DISPLAY_NAME=\"\2\"/" | xargs -L 1)

~$ echo $APP_ID
c...1

~$ echo $APP_DISPLAY_NAME
xyz

Upvotes: 1

hyperupcall
hyperupcall

Reputation: 973

Yes, using jq would be the cleanest way:

str='[
  "c...1",
  "xyz"
]'

# The '.[N]' syntax gets the Nth item in the array
app_id=$(jq -r '.[0]' <<< "$str")

# 'jq' requires feeding the input string through standard input. use the '<<<' to do so
app_display_name=$(jq -r '.[1]' <<< "$str")

printf '%s\n' "id: $app_id"
printf '%s\n' "name: $app_display_name"

Upvotes: 1

Related Questions