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,946
  • 4
  • 26
  • 46
  • 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
  • 761,203
  • 64
  • 569
  • 643
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
  • 80,270
  • 14
  • 142
  • 161
  • Hi - when putting a variable into this script such as: done < <($variable) I get variable value: command not found errors. Do you know why this is? – x3nr0s Jul 28 '16 at 11:47
  • @Xenidious: You need to use a different operator `<<<` for that, refer this page http://tldp.org/LDP/abs/html/x17837.html#HERESTRINGSREF – Inian Jul 28 '16 at 11:53
  • Great! Thanks for the help. – x3nr0s Jul 28 '16 at 12:23