简体   繁体   中英

Unix Loop and add comma for JSON

I'm working on a csv file to import to JSON code. I want to add " in the middle of the echo and in the loop add , to separate no in the end.

This is the variable IMG. (In this example I have 2 URLs, but maybe this can be more.)

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. Then I output the JSON based on the array. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM