Skip to content

Instantly share code, notes, and snippets.

@samrayner
Created August 25, 2017 17:44
Show Gist options
  • Save samrayner/b5bf1b560375fe271595ccb6bac2fab0 to your computer and use it in GitHub Desktop.
Save samrayner/b5bf1b560375fe271595ccb6bac2fab0 to your computer and use it in GitHub Desktop.
#!/bin/bash
#Help to display if the args are wrong
usage() { echo "Usage: $0 -o path/to/output.json" 1>&2; exit 1; }
#Show help if the args are wrong
while getopts ":o:" ARG; do
case "${ARG}" in
o)
OUTPUT_FILE=${OPTARG}
;;
*)
usage
;;
esac
done
shift $((OPTIND-1))
#Show help if the -o arg is missing
if [ -z "${OUTPUT_FILE}" ]; then
usage
fi
#Function to get an absolute path from a relative path
function realpath { echo $(cd $(dirname $1); pwd)/$(basename $1); }
REAL_OUTPUT_PATH=$(realpath $OUTPUT_FILE)
#Begin writing combined JSON
echo "{" > $OUTPUT_FILE
FILES_ADDED=0
#Loop all JSON files in the current dir (including within nested dirs)
find . -type f -name '*.json' | while read FILENAME; do
#Get the contents of the file
JSON=$(cat $FILENAME)
#Trim the opening and closing braces and any surrounding whitespace
TRIMMED="$(echo $JSON | sed -e 's/^[[:space:]]*{[[:space:]]*//' -e 's/[[:space:]]*}[[:space:]]*$//')"
#If we're not reading the output file and the contents is not empty
if [[ $(realpath $FILENAME) != $REAL_OUTPUT_PATH ]] && [[ ! -z $TRIMMED ]]; then
echo "Appending $FILENAME"
#Comma separate consecutive file contents
[[ $FILES_ADDED != 0 ]] && echo -n ', ' >> $OUTPUT_FILE
echo -n "$TRIMMED" >> $OUTPUT_FILE
((FILES_ADDED++))
fi
done
#Finish writing combiend JSON
echo "}" >> $OUTPUT_FILE
#Prettify the output JSON
OUTPUT=$(python -m json.tool $OUTPUT_FILE)
echo "$OUTPUT" > $OUTPUT_FILE
echo "JSON written to $OUTPUT_FILE"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment