jq with bash - read multiple values and save in variable
Sometimes I need to read multiple string values from json, and save them into their own variables as a pre-processing step.
Assigning multiple variables in Bash using process substitution, i.e., <(command)
and using join
with an empty string saved the day.
Let the variable jsonData
hold example json (from another jq TIL) using the here-doc
1
2
3
4
5
6
7
8
9
10
11
12
# load json data
jsonData=$(cat <<EOF
{
"id": 1,
"name": "James"
}
EOF
)
# assign vars using process substitution
read -r var1 var2 < <(echo $jsonData | jq -r '[ .id, .name] | join(" ")')
echo "id=$var1 is called $var2"
References
- Stackoverflow: https://stackoverflow.com/a/43293515
- Assigning multiple variables in Bash using process substitution: https://www.baeldung.com/linux/bash-multiple-variable-assignment
- Difference between process substitution (
<(command)
) and here-document structure (<<
): https://askubuntu.com/questions/678915/whats-the-difference-between-and-in-bash/678919#678919 and https://www.baeldung.com/linux/bash-multiple-variable-assignment and https://www.baeldung.com/linux/heredoc-herestring#here-string
This post is licensed under CC BY 4.0 by the author.