下面是一个for循环的代码段,在其中对txt文件名进行排序。然后,我试图将结果保存为json格式的文件。但是,由于最后插入,
的obj
,导致json格式无效。我如何将for循环中的值转换为json格式?
脚本
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
所需的输出
[
{ "filepath" : "myfiles/test/sdfsd.txt" },
{ "filepath" : "myfiles/test/piids.txt" },
{ "filepath" : "myfiles/test/saaad.txt" },
{ "filepath" : "myfiles/test/smmnu.txt" }
]
电流输出
[
{ "filepath" : "myfiles/test/sdfsd.txt" },
{ "filepath" : "myfiles/test/piids.txt" },
{ "filepath" : "myfiles/test/saaad.txt" },
{ "filepath" : "myfiles/test/smmnu.txt" },
]
最佳答案
请注意,除了第一行以外的每一行都以“,\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
关于linux - 将值从for循环转换为json格式,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30920236/