richardlog

On Java, Agile, Open Source, Architecture and anything in between

Pretty-printing JSON and XML on Mac OSX

Like my colleagues at Avisi I’m an avid OSX user. One of the reasons I like OSX is it gives you the power of Unix right under your fingertips while still providing a nice user interface. 

Now suppose you’re working on RESTful services and you need to verify or debug some JSON output. Digging through an unformatted JSON string can be a real pain. To make a JSON string human readable open up the Terminal and type:

cat unformatted.json | python -m json.tool > formatted.json

This will pretty-print the contents of “unformatted.json” to a new file called “formatted.json”. For this to work you need to have at least Python 2.6 installed. Which is the case when your running Snow Leopard or higher.

The above command assumes you have a file containing the JSON content. When you’re debugging it’s more likely you copied a JSON string to your clipboard from a (remote) log file. To pretty-print the JSON content on your clipboard type:

pbpaste | python -m json.tool > formatted.json

Likewise when you’re dealing with XML instead of JSON type in:

pbpaste | xmllint --format - > formatted.xml

The xmllint program is part of libxml2 and installed by default on OSX.

Happing pretty-printing!

Update: Hacker News thread

  1. nicedexter reblogged this from richardlog and added:
    pbpaste | xmllint --format - > formatted.xml
  2. andresdouglas reblogged this from richardlog
  3. seapomeranian reblogged this from richardlog
  4. richardlog posted this