Skip to content

Instantly share code, notes, and snippets.

@selfagency
Last active February 23, 2022 21:25
Show Gist options
  • Save selfagency/08b4d42b5ac0633c6f816e30beec105e to your computer and use it in GitHub Desktop.
Save selfagency/08b4d42b5ac0633c6f816e30beec105e to your computer and use it in GitHub Desktop.
Super-duper-simple JSON log to JSON converter
#!/bin/bash
####################################################
# Super-duper-simple JSON log to JSON converter #
# #
# Install: #
# $ curl $RAW_GIST_URL -o jl2j #
# $ chmod +x jl2j #
# $ sudo mv jl2j /usr/local/bin #
# #
# Usage: #
# $ jl2j logfile.txt > logfile.json #
# $ jl2j '{"key": "value"} \ #
# {"key": "value"}' > log.json #
# $ echo '{"key": "value"} \ #
# {"key": "value"}' | jl2j > log.json #
####################################################
# Test if the input is empty and pipe in STDIN
if [[ "$1" == "" ]]; then
OUTPUT=$(< /dev/stdin)
# Otherwise check for a help flag
elif [[ "$1" == "-h" ]] || [[ "$1" == "--help" ]]; then
echo "JSON Log to JSON Converter"
echo ""
echo "Usage:"
echo ""
echo "\$ jl2j \$FILE_OR_STRING > new_file.json"
echo "or"
echo "\$ echo \$STRING | jl2j > new_file.json"
echo ""
exit 0
# If not, test if it's a file
elif [[ -f $1 ]]; then
OUTPUT=$(echo "$(cat $1)")
else
# If not, treat it as a string
OUTPUT=$(echo "$1")
fi
# Wrap it in array brackets, replace line breaks with commas,
# and drop the last comma
echo "[ $OUTPUT ]" | tr '}\n' '}, ' | sed 's/.$//'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment