Reputation: 71
My JSON data:
{
"Tags": [
{ "Key": "Team", "Value": "AA" },
{ "Key": "Division", "Value": "BB" },
{ "Key": "Name", "Value": "CC" }
]
}
I'd like to display value of Name ("CC" in example above). If this value is missing "N/A" should be displayed. What I'm looking for is pure jq replacement of this jq and bash mix:
a=$( cat json | jq -r '.Tags[] | select( .Key=="Name" ) | .Value' );
if [ -z $a ]; then a="N/A"; fi
echo $a
Upvotes: 1
Views: 611
Reputation: 71
Here is the perfect solution from David Tolnay:
https://github.com/stedolan/jq/issues/976
Quoting it here:
Try this:
jq -r '.Tags | from_entries | .Name // "N/A"'
This converts the list of key/value pairs to a map using from_entries, then picks out the "Name" in the map. Then it uses the "alternative operator" // to produce "N/A" if Name was not in the map.
This requires jq 1.5 in order to understand capitalized "Key" and "Value" in from_entries. If you are stuck on jq 1.4 or older, you need to explicitly convert them to lowercase:
jq -r '.Tags | map({key:.Key, value:.Value}) | from_entries | .Name // "N/A"'
Upvotes: 2
Reputation:
Use the alternative operator, //
.
jq -r '.Tags[] | select(.Key == "Name") | .Value // "N/A"'
Upvotes: 0