-3

I am reading an array from a file

file.json

{
  "content": ["string with spaces", "another string with spaces", "yet another string with spaces"]
}
#!/bin/bash
GROUP_ID_TEMP=( $(IFS=','; jq -r '.content' file.json) )

why does jq read content print or echo content as space separated array for the below codeblock at the whitespace rather than the comma ',' as explicitly stated?

for each in "${GROUP_ID_TEMP[@]}"
do
    echo "$each" >> "file.txt"
done
mibbit
  • 4,997
  • 3
  • 26
  • 34
  • Please edit your Q to include your expected output. Did you try taking your cmd-line apart and adding back each element to see where it fails, i.e. 1) `jq -r '.content' file.json` 2) `IFS=,;jq -r '.content' file.json` 3) `echo $(IFS=','; jq -r '.content' file.json)` ... etc? Good luck. – shellter May 14 '20 at 02:09
  • Are you expecting `IFS=,` to have an effect on `jq ..` ? If yes, try removing the `;`, however I don't think that will solve your problem. Good luck. – shellter May 14 '20 at 02:10
  • Please note that if this is an XYQuestion for "How do I turn a JSON string array into a bash array?", you should ask that separately because this is not a good means to that end – that other guy May 14 '20 at 02:40
  • 1
    duplicate of [How do I convert json array to bash array of strings with jq?](https://stackoverflow.com/questions/35005893/how-do-i-convert-json-array-to-bash-array-of-strings-with-jq) – oguz ismail May 14 '20 at 02:56

1 Answers1

1

Here's an easier way to reproduce your problem:

var=( $(IFS=','; echo "foo,bar" ) )
declare -p var

What you expect is declare -a var=([0]="foo" [1]="bar") but what you get is declare -a var=([0]="foo,bar")

This happens because IFS affects word splitting and not program output. Since there is no word splitting in the scope of your variable, it doesn't affect anything.

If you instead define it in the scope that does word splitting, i.e. the scope in which the $(..) expansion happens:

IFS=','
var=( $(echo "foo,bar") )

then you get the result you expect.

that other guy
  • 116,971
  • 11
  • 170
  • 194