summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorclaw0ry <me@claw0ry.net>2024-12-19 16:45:57 +0100
committerclaw0ry <me@claw0ry.net>2024-12-20 08:15:32 +0100
commitd6f1935c1e3e35359873b3fffc8021616a9ab45b (patch)
tree204907c01a07015db61a71956e517b6d1e6d8aec
parentimprove setup in convert-svg-to-png (diff)
posts: format json with python
-rw-r--r--content/posts/format-json-with-python.md49
1 files changed, 49 insertions, 0 deletions
diff --git a/content/posts/format-json-with-python.md b/content/posts/format-json-with-python.md
new file mode 100644
index 0000000..b7524a1
--- /dev/null
+++ b/content/posts/format-json-with-python.md
@@ -0,0 +1,49 @@
+---
+title: "Format JSON with Python (oneliner)"
+description: "Use python to format JSON data"
+date: 2024-12-19T16:00:00+02:00
+tags: ['python', 'json', 'cli']
+---
+
+I'm experimenting with getting by without Language Server Protocol (LSP), and today I came a accross a large JSON file that was compressed into a single line. As I usually do I typed `<leader>+f` to make the LSP format the file.. I soon realized that I had to find another way without my LSP.
+
+<!--more-->
+
+So I came across this python3 module `json.tool` that can format JSON input.
+
+To format a file:
+
+```bash
+python3 -m json.tool unformatted.json > formatted.json
+```
+
+To format from stdin:
+
+```bash
+cat unformatted.json | python3 -m json.tool -- > formatted.json
+```
+
+We can also do it from within vim thanks to vim's support of external commands. Let's say we have the following line in our editor.
+
+```json
+{ "name": "claw0ry", "website": "https://claw0ry.net"}
+```
+
+Let's select the line with `V` and then type
+
+```
+:'<,'>!python3 -m json.tool --
+```
+
+And VOILA, the data is formatted.
+
+```json
+{
+ "name": "claw0ry",
+ "website": "https://claw0ry.net"
+}
+```
+
+## Alternative
+
+Another alternative is to use `jq` which is way less characters to type, but it requires you to have the tool installed and the python module is built-in.