[英]Unix Loop and add comma for JSON
I'm working on a csv file to import to JSON code. 我正在处理要导入JSON代码的csv文件。 I want to add "
in the middle of the echo
and in the loop add ,
to separate no in the end. 我想补充"
在中部echo
,并在循环加,
分离不到底。
This is the variable IMG. 这是变量IMG。 (In this example I have 2 URLs, but maybe this can be more.) (在此示例中,我有2个URL,但也许可以更多。)
img="https://example.com/img/p/8/1/1/811.jpg,https://example.com/img/p/8/0/8/808.jpg"
This is my code: 这是我的代码:
img=$(echo $img | tr -d '"')
echo " \"pictures\":[" >>"$output_filename"
for imgt in ${img//,/ }
do
echo " {\"source\":$imgt} " >>"$output_filename"
done
echo ']' >>"$output_filename"
echo '}' >>"$output_filename"
The result 结果
"pictures":[
{"source":"https://quierotodo.com.ar/img/p/8/1/1/811.jpg}
{"source":https://quierotodo.com.ar/img/p/8/0/8/808.jpg"}
]}
Expected result 预期结果
"pictures":[
{"source":"https://quierotodo.com.ar/img/p/8/1/1/811.jpg"},
{"source":"https://quierotodo.com.ar/img/p/8/0/8/808.jpg"}
]}
Can you suggest some option to add ,
in the middle of the code not in the last? 您能建议在代码中间添加一些选项,
而不是在最后吗?
I modified your script a bit and: 我对您的脚本进行了一些修改,并:
#!/bin/bash
#
img="https://example.com/img/p/8/1/1/811.jpg,https://example.com/img/p/8/0/8/808.jpg"
# Remove the double quotes
img=$(echo $img | tr -d '"')
# Split on the comma, and create an array
IFS=',' read -ra images <<< "$img"
# Start the JSON
echo "\"pictures\":["
# loop through the images, and output the JSON
# keep track of the index of output items
counter=1
for image in "${images[@]}"
do
echo -n " {\"source\":\"$image\"}"
# Add a comma unless it is the last element in the array
if [ $counter -lt ${#images[@]} ]
then
echo ","
else
echo ""
fi
(( counter = counter + 1 ))
done
# Close the JSON
echo "]}"
I transformed $img
into an array. 我将$img
转换为数组。 Then I output the JSON based on the array. 然后,我基于数组输出JSON。 Unless it is the last item in the array, I add a comma next to the item. 除非它是数组中的最后一项,否则我将在该项目旁边添加一个逗号。
The output is: 输出为:
$ ./so.bash
"pictures":[
{"source":"https://example.com/img/p/8/1/1/811.jpg"},
{"source":"https://example.com/img/p/8/0/8/808.jpg"}
]}
You will have to modify it to add an opening {
somewhere. 您将必须对其进行修改以在某处添加一个开口{
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.