Bash scripts that writes a json array to a json file

Viewed 48

I am trying to write a bash script that generates uuids and writes that to a file, in a json array format. I have written a simple code that generates the id and writes to a file but the issues i am running into are;

here is my own implementation

function uud {
     for ((i=1;i<=$1;i++));
     do 
         echo "\`uuidgen\`", >> $file
     done 
 }

 for file in file1.json file2.json;
 do 
     $( uud $1)
done
  1. I am having issues with converting the ids into strings.
  2. Converting the results to arrays.

Currently my solution prints the ids into the file in this format

caca8fef-42d6-4b21-9d6b-0e40d348bd53,
e6e12fb5-4304-4ba9-b895-931bb4b58fbf,
df699ecd-d887-413e-8383-2a98ac2fa22f,

and this is what i want to acheive, How can I go about getting this result?

[
"caca8fef-42d6-4b21-9d6b-0e40d348bd53",
"e6e12fb5-4304-4ba9-b895-931bb4b58fbf",
"df699ecd-d887-413e-8383-2a98ac2fa22f"
]
3 Answers

Use jq to generate the JSON.

uud () {
    for ((i=0; i< $1; i++)); do
        uuidgen
    done
}

for file in file1.json file2.json; do
    uud 5 | jq -Rs 'rtrimstr("\n") | split("\n")' > "$file"
done

-Rs reads the entire input into a single JSON string, which you then split (after removing the trailing newline) on newlines to produce the desired array.


One blogger suggests using two jq processes, which is more expensive but arguably simpler:

for file in file1.json file2.json; do
   uud | jq -R . | jq -s . > "$file"
done

I have adjusted slightly your script, try it:

function uud {
    echo "[" > $file
    for ((i=1;i<$1;i++));
    do 
        echo \"$(uuidgen)\", >> $file
    done 
    echo \"$(uuidgen)\" >> $file           # last item in array without comma 
    echo "]" >> $file
 }

for file in file1.json file2.json;
do 
    $( uud $1)
done

Or execute it here and check the result.

After you've run your existing loop...

#!/bin/sh
cat > ed1 <<EOF
%s/^/"/g
%s/$/"/g
$s/,//
1i
[
.
$a
]
.
wq
EOF

ed -s file < ed1
Related