Kennis Blogs Pretty-printing JSON and XML on Mac OSX

Pretty-printing JSON and XML on Mac OSX

Like the rest of 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. Here's a simple solution...

 

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.

 

Happy pretty-printing!

 

Original post: Richard Kettelerij's tumblelog. Discussion on HackerNews.