Converting values from a for loop to json format
Below is a snippet of a for loop in which I am sorting txt filenames. Then I try to save the results in a json format file. However, this results in an invalid json format due to the latter ,
being inserted into obj
. How can I convert values from a for loop to json?
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" },
]
+3
source to share
2 answers
Note that every line except the first starts 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
+2
source to share
Not sure what the job is for the JSON conversion, but you can change your logic to get the o / p you want. Try adding it at the beginning rather than the end, but additional validation will affect performance.
dir = "myfiles/test/"
flag = false
echo "[" >> test.json
for dir in "${array[@]}"; do
#reverse the result of comparisons
if [ $flag ]
echo ","
else
flag = true
fi
file=$(find "$dir" -maxdepth 1 -type f -iname '*.txt' | awk "NR==$i")
[[ -n $file ]] && echo -n "{ \"filepath\" : \"$file\" }" >> test.json
done
echo "]" >> test.json
+1
source to share