Skip to content
Advertisement

Converting values from for loop to json format

Below is a snippet of a for loop where I sort txt file names. I am then trying to save the results in a json format file. However it results in an invalid json format due to the last , inserted in obj. How could i convert to json format the values from the for loop?

script

dir = "myfiles/test/"
echo "[" >> test.json
for dir in "${array[@]}"; do
        #reverse the result of comparisons
        file=$(find "$dir" -maxdepth 1 -type f -iname '*.txt' | awk "NR==$i")
        [[ -n $file ]] && echo "{ "filepath" : "$file" },"  >> test.json
done
echo "]" >> test.json

Desired output

[
{ "filepath" : "myfiles/test/sdfsd.txt" },
{ "filepath" : "myfiles/test/piids.txt" },
{ "filepath" : "myfiles/test/saaad.txt" },
{ "filepath" : "myfiles/test/smmnu.txt" }
]

Current output

[
{ "filepath" : "myfiles/test/sdfsd.txt" },
{ "filepath" : "myfiles/test/piids.txt" },
{ "filepath" : "myfiles/test/saaad.txt" },
{ "filepath" : "myfiles/test/smmnu.txt" },
]

Advertisement

Answer

Observe that each line except the first begins with “,n”.

dir="myfiles/test/"

prefix=""
echo "[" >> test.json
for dir in "${array[@]}"; do
        #reverse the result of comparisons
        file=$(find "$dir" -maxdepth 1 -type f -iname '*.txt' | awk "NR==$i")
        [[ -n $file ]] && 
                printf '%b{ "filepath": "%s" }' $prefix "$file" >> test.json
        prefix=",n"
done
echo
echo "]" >> test.json
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement