From d6f1935c1e3e35359873b3fffc8021616a9ab45b Mon Sep 17 00:00:00 2001 From: claw0ry Date: Thu, 19 Dec 2024 16:45:57 +0100 Subject: posts: format json with python --- content/posts/format-json-with-python.md | 49 ++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 content/posts/format-json-with-python.md (limited to 'content/posts') 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 `+f` to make the LSP format the file.. I soon realized that I had to find another way without my LSP. + + + +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. -- cgit v1.2.3