-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
4
  • 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. Commented May 14, 2020 at 2: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. Commented May 14, 2020 at 2: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 Commented May 14, 2020 at 2:40
  • 1
    duplicate of How do I convert json array to bash array of strings with jq? Commented May 14, 2020 at 2:56

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.