gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 11:08:21 26 4
gpt4 key购买 nike

下面是我对 txt 文件名进行排序的 for 循环片段。然后我试图将结果保存在 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com