JSON encode clipboard contents back to clipboard with Bash and Python

Here’s a Bash one-liner to JSON-encode the current contents of the clipboard and replace the clipboard contents with the JSON-encoded output:

xclip -o | python -c 'import sys;import json;print(json.dumps(sys.stdin.read().strip()))' | tee >(xclip -selection clipboard)

The equivalent on Mac is:

pbpaste | python -c 'import sys;import json;print(json.dumps(sys.stdin.read().strip()))' | pbcopy

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

alias jec='xclip -selection clipboard -o | python -c "import sys;import json;print(json.dumps(sys.stdin.read().strip()))" | tee >(xclip -selection clipboard)'

Then you can copy some string text, run jec, and then paste the JSON-encoded string back from the clipboard.

This is handy when you need to double encode a JSON string to be able to nest it inside an outer JSON object, e.g.

# ctrl + c: {"this":"is some json"}

jec

# ctrl + v: "{\"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: JSON encode clipboard contents back to clipboard with Bash and Python