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
JavaScript
x
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
JavaScript
[
{ "filepath" : "myfiles/test/sdfsd.txt" },
{ "filepath" : "myfiles/test/piids.txt" },
{ "filepath" : "myfiles/test/saaad.txt" },
{ "filepath" : "myfiles/test/smmnu.txt" }
]
Current output
JavaScript
[
{ "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”.
JavaScript
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