Save tree view json to file using jq library

Viewed 206

I have like this json data in my case:

sshpass -p $PASSWORD ssh -o StrictHostKeyChecking=no $LOGIN /bin/bash -s << EOT

echo "Saving to file.."

USER_DATA="{\"id\":"$USER_ID",\"sha\":"$USER_SHA"}"
echo "{\"id\":"$PRODUCT_ID",\"user\":"$USER_DATA"}" | jq -re > ~/user.json

EOT

When I tried save this json to file get error with message:

parse error: Unmatched '}' at line 1, column 21

How I can save correctly my json data to file?

1 Answers

You should use jq to create your json. Try something like this :

sshpass -p $PASSWORD ssh -o StrictHostKeyChecking=no $LOGIN /bin/bash -s << EOT

echo "Saving to file.."

jq --arg id "$PRODUCT_ID" -n '{$id}' | \
jq --arg id "$USER_ID" \
   --arg sha "$USER_SHA" \
   --arg user "user" \
   '.[$user]={$id, $sha}' > ~/user.json

EOT

Explanations:

  • --arg id "$PRODUCT_ID" : create a variable for jq, called id which contains the value taken from $PRODUCT_ID
  • -n '{$id}' : create a new json template
    • This will take the variable name as well as its value
    • Here, this creates the json {id : $id}
  • jq ... | jq ... : we pass the output of the 1st jq command as the input of the 2nd command
  • '.[$user]={$id, $sha}' : we add new elements to the input
    • .[$user] : the element name from the $user variable
    • {$id, $sha} : will create an object from the variables, i.e. {id : $id, sha : $sha}
    • the whole command creates the element : user : {id : $id, sha : $sha}
Related