3

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:

James
Brown
Matthew
Thompson

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

Thanks.

x3nr0s
  • 1,661
  • 1
  • 21
  • 40
  • you should provide a way to get `getNames` so we can test. Also, most probably the problem lies in lack of quotes: say `echo "$getNames"` to preserve format. – fedorqui Jul 28 '16 at 10:25
  • Unfortunately I can't post the JSON as it is confidential. I tried placing quotes around $getNames however this did not fix my issue! – x3nr0s Jul 28 '16 at 10:30

2 Answers2

4

Just use mapfile command to read multiple lines into an array like this:

mapfile -t myArray < <(jq -r .user[].name <<< "$getNames")
anubhava
  • 713,503
  • 59
  • 514
  • 593
4

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

#!/bin/bash

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

# To print the array
printf '%s\n' "${myArray[@]}"
Inian
  • 71,145
  • 9
  • 121
  • 139