Juha-Matti Santala
Community Builder. Dreamer. Adventurer.

Pretty print and validate JSON on command line with json.tool

Batteries included is a blog series about the Python Standard Library. Each day, I share insights, ideas and examples for different parts of the library. Blaugust is an annual blogging festival in August where the goal is to write a blog post every day of the month.

Python is not only a great programming language but its built-in command line tools make it a nice companion on terminal as well.

Today’s small but powerful example is using json.tool from json module as a command line tool to pretty print and validate JSON.

Let’s say we have a JSON file example.json that looks like this:

{ "glossary": { "title": "example glossary", "GlossDiv": { "title": "S", "GlossList": { "GlossEntry": { "ID": "SGML", "SortAs": "SGML", "GlossTerm": "Standard Generalized Markup Language", "Acronym": "SGML", "Abbrev": "ISO 8879:1986", "GlossDef": { "para": "A meta-markup language, used to create markup languages such as DocBook.", "GlossSeeAlso": ["GML", "XML"] }, "GlossSee": "markup" } } } } }

we can then feed it to Python:

python -m json.tool < example.json

and out comes a prettified JSON structure for easier reading:

{
    "glossary": {
        "title": "example glossary",
        "GlossDiv": {
            "title": "S",
            "GlossList": {
                "GlossEntry": {
                    "ID": "SGML",
                    "SortAs": "SGML",
                    "GlossTerm": "Standard Generalized Markup Language",
                    "Acronym": "SGML",
                    "Abbrev": "ISO 8879:1986",
                    "GlossDef": {
                        "para": "A meta-markup language, used to create markup languages such as DocBook.",
                        "GlossSeeAlso": [
                            "GML",
                            "XML"
                        ]
                    },
                    "GlossSee": "markup"
                }
            }
        }
    }
}

Coming in Python 3.14, you can omit the .tool part and feed the JSON into python -m json thanks to the work of Trey Hunner. I think that’s a great fix/addition as it requires users to remember one less thing when using the command line interface.