Python · Copy to clipboard
Format JSON on Clipboard
Pretty-prints the JSON on the clipboard with two-space indentation. Type "min" to minify it instead.
- Language
- Python
- Output
- Copy to clipboard
- Keyword
json- Arguments
- min (optional) (optional)
- Licence
- MIT
- Author
- Docktopus
- File
- format-json.py (1.0 KB)
- Downloads
- 0
In Docktopus: Settings → Scripts → Browse Community Scripts. Read the source before you run any script.
Source
format-json.py · sha256 1225ca73ab36…#!/usr/bin/env python3
# @docktopus.schemaVersion 1
# @docktopus.title Format JSON on Clipboard
# @docktopus.mode copy
# @docktopus.icon curlybraces
# @docktopus.keyword json
# @docktopus.description Pretty-prints the JSON on the clipboard with two-space indentation. Type "min" to minify it instead.
# @docktopus.argument1 {"type": "text", "placeholder": "min (optional)", "optional": true}
# @docktopus.author Docktopus
import json
import subprocess
import sys
text = subprocess.run(["/usr/bin/pbpaste"], capture_output=True, text=True).stdout.strip()
if not text:
sys.exit("The clipboard is empty.")
try:
data = json.loads(text)
except json.JSONDecodeError as error:
sys.exit(f"The clipboard is not valid JSON: {error.msg} at line {error.lineno}, column {error.colno}.")
minify = len(sys.argv) > 1 and sys.argv[1].strip().lower() in {"min", "minify", "m"}
if minify:
print(json.dumps(data, ensure_ascii=False, separators=(",", ":")), end="")
else:
print(json.dumps(data, ensure_ascii=False, indent=2), end="")