将值从for循环转换为json格式

时间:2015-06-18 15:55:21

标签: linux unix

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

2 个答案:

答案 0 :(得分:2)

观察除第一行以外的每一行都以“,\ 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

答案 1 :(得分:1)

不确定JSON转换的工作原理,但您可以更改逻辑以获得所需的o / p。尝试在开始时添加它而不是结束,但额外的检查会影响性能。

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