Xenidious Xenidious - 1 year ago 61
JSON Question

Bash - Only go next index when new line occurs, instead of white space?

I'm parsing a JSON response with a tool called jq.
The output from jq will give me a list of full names in my command line.

I have the variable getNames which contains JSON, for example:

"count": 49,
"user": [{
"username": "jamesbrown",
"name": "James Brown",
"id": 1
}, {
"username": "matthewthompson",
"name": "Matthew Thompson",
"id": 2

I pass this through JQ to filter the json using the following command:

echo $getNames | jq -r .user[].name

Which gives me a list like this:

James Brown
Matthew Thompson

I want to put each one of these entries into a bash array, so I enter the following commands:

declare -a myArray
myArray=( `echo $getNames | jq -r .user[].name` )

However, when I try to print the array using:

printf '%s\n' "${myArray[@]}"

I get the following:


How do I ensure that a new index is created after a new line and not a space? Why are the names being separated?


Answer Source

A simple script in bash to feed each line of the output into the array myArray.


while IFS= read -r line; do
    [[ $line ]] || break  # break if line is empty
done < <(jq -r .user[].name <<< "$getNames")

# To print the array
printf '%s\n' "${myArray[@]}"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download