将值从for循环转换为json格式 [英] Converting values from for loop to json format

查看:54
本文介绍了将值从for循环转换为json格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是for循环的一小段,在其中我对txt文件名进行了排序.然后,我试图将结果保存为json格式的文件.但是,由于最后一个插入了 obj 中,导致json格式无效.我该如何将for循环中的值转换为json格式?

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?

脚本

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"开头.

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

这篇关于将值从for循环转换为json格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆