Browse files

Allow piping to the `json` function

  • Loading branch information...
1 parent 6b75bfc commit 9b0af44766d2a2cc61ae0142ac3ec9f0bed75674 @mathiasbynens committed Dec 28, 2011
Showing with 10 additions and 2 deletions.
  1. +10 −2 .functions
View
12 .functions
@@ -9,9 +9,17 @@ function httpcompression() {
encoding="$(curl -LIs -H 'User-Agent: Mozilla/5 Gecko' -H 'Accept-Encoding: gzip,deflate,compress,sdch' "$1" | grep '^Content-Encoding:')" && echo "$1 is encoded using ${encoding#* }" || echo "$1 is not using any encoding"
}
-# Syntax-highlight JSON files
+# Syntax-highlight JSON strings or files
function json() {
- python -mjson.tool <<< "$*" | pygmentize -l javascript
+ if [ -p /dev/stdin ]; then
+ # piping, e.g. `echo '{"foo":42}' | json`
+ while read data; do
+ python -mjson.tool <<< "$data" | pygmentize -l javascript
+ done
+ else
+ # e.g. `json '{"foo":42}'`
+ python -mjson.tool <<< "$*" | pygmentize -l javascript
+ fi
}
# All the dig info

3 comments on commit 9b0af44

@janmoesen

First, you should use read -r to prevent unwanted unescaping:

-----[ 14:43:07 ] (!8180) [ :-) ] janmoesen@janmoesen ~ 
$ read <<< 'foo\nbar'; echo "$REPLY"
foonbar
-----[ 14:43:30 ] (!8181) [ :-) ] janmoesen@janmoesen ~ 
$ read -r <<< 'foo\nbar'; echo "$REPLY"
foo\nbar

(I am guilty of using read instead of read -r quite often, myself. Don't take this as me being holier than thou.)

Apart from that, I don't think this snippet does what you think it should do. Now you spawn the Python tool for every line of input, as opposed to once for all lines combined. Get rid of the whole while loop, and simply let the python process handle the input:

if [ -p /dev/stdin ]; then
    python -mjson.tool | pyg…
@mathiasbynens

Don't take this as me being holier than thou.

No worries; as a shell n00b, I very much appreciate your 31337 feedback!

Get rid of the whole while loop, and simply let the python process handle the input […]

How do I get the input when it’s piped? Is there a variable for it? (The fact that I didn’t know is what made me use while read x.)

Update: Holy shit, the arguments are passed over automatically!!1

@mathiasbynens

Fixed in 307c425, thanks again @janmoesen!

Please sign in to comment.