I'm trying to print array data from json in bash and I use jq for this purpose. The problem is, if the value of the record contain spaces, it will messed up the output. Below is the bash script that demonstrates this problem:
This is the full source code (required jq):
#!/bin/bash
# 1) Declare a sample json with 3 records:
json_data=$(cat <<EOF
{
"records":[
{
"name":"record1",
"value":"\"1.this-is-string-value-of-record-1-with-no-spaces\""
},
{
"name":"record2",
"value":"\"2. this is string value of record 2 with spaces\""
},
{
"name":"record3",
"value":"\"3. this is string value of record 3 with spaces\""
}
]
}
EOF
)
# 2) create the first list of array from .name
record=($(echo "${json_data}" | jq -r ".records[].name" | tr '\n' ' '))
# 3) create the second list of array from .value
record2=($(echo "${json_data}" | jq -r ".records[].value" | tr '\n' ' '))
# 4) printout the array
for i in "${!record[@]}"; do
echo "The record [ ${record[i]} ] belongs to [ ${record2[i]} ]"
done
Output:
The record [ record1 ] belongs to [ "1.this-is-string-value-of-record-1-with-no-spaces" ]
The record [ record2 ] belongs to [ "2. ]
The record [ record3 ] belongs to [ this ]
Expected output:
The record [ record1 ] belongs to [ 1.this-is-string-value-of-record-1-with-no-spaces ]
The record [ record2 ] belongs to [ 2. this is string value of record 2 with spaces ]
The record [ record3 ] belongs to [ 3. this is string value of record 3 with spaces ]
Could you explain why it does not accept spaces value? Thanks.