jsonfmt

learn how to use python to format JSON files

Created: by Pradeep Gowda Updated: Oct 10, 2023 Tagged: python · json · code

Sometimes you would like to format a JSON file, and you wish a command called jsonfmt like gofmt would be handy. If you have Python3 installed on your system, you already have such a tool installed, its just called with a different name.

Let’s say you have this file - two.json 1.


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

Not very readable, is it? You can “pretty-print” it like this:

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

You can output the formatted JSON to a file like this:

$ python3 -m json.tool two.json three.json

Further, you can sort the keys with the --sort-keys option

$ python3 -m json.tool two.json --sort-keys

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

CAUTION: The one downside to this tool is, you can’t do an “in-place” formatting. That is, if you try – $ python3 -m json.tool two.json two.json, it will overwrite the original file.

If you want further explore json related tools, look at my json and jq pages.