MaryCoding
MaryCoding

Reputation: 664

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" },
]

Upvotes: 3

Views: 101

Answers (2)

user464502
user464502

Reputation: 2373

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

Upvotes: 2

MrocKK
MrocKK

Reputation: 51

Not sure what's the work around for JSON conversion, but you can change your logic to get the desired o/p. Try adding it at start instead of end, but the extra check will affect the 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

Upvotes: 1

Related Questions