Minify JSON clipboard contents back to clipboard with Bash and Python

Here’s a Bash one-liner to minify JSON in the current contents of the clipboard and replace the clipboard contents with the minified JSON:

xclip -selection clipboard -o | python3 -c "import sys;import json;print(json.dumps(json.loads(sys.stdin.read()),separators=(\",\",\":\")))" | tee >(xclip -selection clipboard)

The equivalent on Mac is:

pbpaste | python3 -c "import sys;import json;print(json.dumps(json.loads(sys.stdin.read()),separators=(\",\",\":\")))" | pbcopy

To set it as an alias in Linux (mcj for “minify clipboard json”):

alias mcj='xclip -selection clipboard -o | python3 -c "import sys;import json;print(json.dumps(json.loads(sys.stdin.read()),separators=(\",\",\":\")))" | tee >(xclip -selection clipboard)'

Then you can copy some JSON, run mcj, and then paste the minified JSON back from the clipboard, e.g.

{
    "this": "is some json"
}
mcj
{"this":"is some json"}

The three clipboard JSON manipulation aliases I have set up are:

alias jec='xclip -selection clipboard -o | python3 -c "import sys;import json;print(json.dumps(sys.stdin.read().strip()))" | tee >(xclip -selection clipboard)'
alias pcj='xclip -selection clipboard -o | python3 -m json.tool | tee >(xclip -selection clipboard)'
alias mcj='xclip -selection clipboard -o | python3 -c "import sys;import json;print(json.dumps(json.loads(sys.stdin.read()),separators=(\",\",\":\")))" | tee >(xclip -selection clipboard)'

View post: Minify JSON clipboard contents back to clipboard with Bash and Python