Beautifying JSON In Emacs

I really like JSON. It’s the perfect mechanism for serializing data; much better, in my opinion, than the typical XML solution. That said, I don’t use it enough to justify installing one of the really nice packages that deal with it such as Steve Yegge’s js2-mode or Edward O’Connor’s json.el. Still, I thought it would be nice to have an Emacs utility that could transform JSON into a standard, readable format.

The other day I came across a post in Richard Ketteierij’s richardlog blog about pretty-printing JSON and XML on Mac OSX. His post had nothing to do with Emacs; it was merely a way of writing reformatted JSON to a file. It occurred to me that this was just what I needed for the occasional lightweight reformatting of JSON. It should work for any system with Python 2.6 or greater installed.

It turns out that the Python distribution comes with a json.tool module that does the work of reformating JSON. For example, here

{"father":{"name":"John Smith", "age":45, "employer":"YoYodyne, inc."},
"mother":{"name":"Wilma Smith", "age":42},
"children":[{"name":"William Smith", "age":15},
         {"name":"Sally Smith","age":17}]}

is some JSON that I used when I first wrote about JSON back in 2009 on my old blog. It’s easy to run this through json.tool by selecting the code and typing 【Ctrl+u Meta+|python -m json.tool. Doing that yields

{
    "children": [
        {
            "age": 15, 
            "name": "William Smith"
        }, 
        {
            "age": 17, 
            "name": "Sally Smith"
        }
    ], 
    "father": {
        "age": 45, 
        "employer": "YoYodyne, inc.", 
        "name": "John Smith"
    }, 
    "mother": {
        "age": 42, 
        "name": "Wilma Smith"
    }
}

which is more readable and standardized in the sense that the items are in alphabetical order. As I said, it’s a simple and lightweight solution but quite handy if you deal with JSON only occasionally. If you use JSON a lot you probably have one of the packages mentioned above installed already (or should have).

Update: an example of to get rid of redundant “example.”

This entry was posted in General and tagged . Bookmark the permalink.