Skip to content

Instantly share code, notes, and snippets.

@Vovan-VE
Created January 20, 2024 08:00
Show Gist options
  • Save Vovan-VE/15429cb5cf135b224346bf2816029c6f to your computer and use it in GitHub Desktop.
Save Vovan-VE/15429cb5cf135b224346bf2816029c6f to your computer and use it in GitHub Desktop.
JSON Uglify (Bash)
#!/bin/bash
SELF="$( basename "$0" )"
# new-line char is skipped here
while read -r LINE; do
while [ -n "$LINE" ]; do
# skip whitespaces
[[ "$LINE" =~ ^[$' \t\r\n']+ ]] && {
PART="${BASH_REMATCH[0]}"
LINE="${LINE:${#PART}}"
}
CHAR="${LINE:0:1}"
PART=''
case "$CHAR" in
[\][{},:])
PART="$CHAR"
;;
\")
[[ "$LINE" =~ ^\"([^\"\\]|\\.)*\" ]] || {
echo "$SELF: cannot match \"string\"" >&2
exit 2
}
PART="${BASH_REMATCH[0]}"
;;
[-0-9])
[[ "$LINE" =~ ^-?(0|[1-9][0-9]*)(\.[0-9]+)?([eE][-+]?[0-9]+)? ]] || {
echo "$SELF: cannot match number" >&2
exit 2
}
PART="${BASH_REMATCH[0]}"
;;
# null | true, assuming the input IS already correct JSON
n|t)
PART="${LINE:0:4}"
;;
# false, assuming the input IS already correct JSON
f)
PART="${LINE:0:5}"
;;
?)
echo "$SELF: unexpected char $CHAR" >&2
exit 2
esac
echo -n "$PART"
LINE="${LINE:${#PART}}"
done
done
# new-line in the end
#echo ''
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment