Skip to content

Instantly share code, notes, and snippets.

@mathew-fleisch
Created January 13, 2020 16:04
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mathew-fleisch/9cca52c25af545b379bde954d8b76745 to your computer and use it in GitHub Desktop.
Save mathew-fleisch/9cca52c25af545b379bde954d8b76745 to your computer and use it in GitHub Desktop.
Working with JSON in Bash
#!/bin/bash
# Methods for working with json in bash
# ************************************************************* #
# Setup
BUCKET_NAME=testbucket
OBJECT_NAME=testworkflow-2.0.1.jar
TARGET_LOCATION=/opt/test/testworkflow-2.0.1.jar
# ************************************************************* #
# Using JQ
JSON_STRING=$(jq -c -n \
--arg bn "$BUCKET_NAME" \
--arg on "$OBJECT_NAME" \
--arg tl "$TARGET_LOCATION" \
'{bucketname: $bn, objectname: $on, targetlocation: $tl}')
echo "JSON via jq:"
echo "$JSON_STRING"
echo ""
# ************************************************************* #
# Using printf
echo "JSON via printf:"
JSON_FMT='{"bucketname":"%s","objectname":"%s","targetlocation":"%s"}\n'
printf "$JSON_FMT" "$BUCKET_NAME" "$OBJECT_NAME" "$TARGET_LOCATION"
echo ""
# ************************************************************* #
# Using concatenation
echo "JSON via string concatenation:"
JSON_STRING='{"bucketname":"'"$BUCKET_NAME"'","objectname":"'"$OBJECT_NAME"'","targetlocation":"'"$TARGET_LOCATION"'"}'
echo "$JSON_STRING"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment