-
-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
[bin] improve prettyjson helper script to support reading/writing cli…
…pboard/STDIN/STDOUT as well as using different tools as installed (json_pp, jq, python -m json.tool) closes #18
- Loading branch information
1 parent
70dd774
commit f4415b0
Showing
1 changed file
with
52 additions
and
3 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,3 +1,52 @@ | ||
#!/bin/bash | ||
# Simple JSON pretty print for contents on your cliboard | ||
pbpaste | json_pp | pbcopy | ||
#!/usr/bin/env zsh | ||
|
||
# Simple JSON pretty print helper script | ||
|
||
# Import our common helper scripts | ||
source "${ZSH}/lib/_helpers" | ||
|
||
getInput() { | ||
if [ -t 0 ]; then | ||
echo >&2 "Formatting JSON in clipboard..." | ||
INPUT=$(pbpaste) | ||
else | ||
echo >&2 "Formatting JSON from STDIN..." | ||
INPUT=$(cat -) | ||
fi | ||
} | ||
|
||
formatJson() { | ||
# https://stackoverflow.com/questions/20265439/how-can-i-pretty-print-a-json-file-from-the-command-line/24951417 | ||
if is_installed "json_pp" &>/dev/null; then | ||
echo >&2 "Using 'json_pp'..." | ||
|
||
FORMATTED=$(echo "$INPUT" | json_pp) | ||
elif is_installed "jq" &>/dev/null; then | ||
echo >&2 "Using 'jq'..." | ||
|
||
FORMATTED=$(echo "$INPUT" | jq) | ||
elif is_installed "python" &>/dev/null; then | ||
echo >&2 "Using 'python -m json.tool'..." | ||
|
||
FORMATTED=$(echo "$INPUT" | python -m json.tool) | ||
else | ||
echo >&2 "ERROR: no supported JSON pretty print tools installed (supported: json_pp, jq, python -m json.tool)" | ||
exit 1 | ||
fi | ||
} | ||
|
||
handleOutput() { | ||
if [ -t 1 ]; then | ||
echo >&2 "Writing formatted JSON back into the clipboard..." | ||
echo "$FORMATTED" | pbcopy | ||
else | ||
echo >&2 "Writing formatted JSON to STDOUT..." | ||
echo "$FORMATTED" | ||
fi | ||
} | ||
|
||
getInput | ||
|
||
formatJson | ||
|
||
handleOutput |