Development · Mac

Pretty Printing JSON / XML in Human Readable Form on Mac OSX

Print JSON in Human Readable Form

If 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. Assuming that your unformatted JSON file is in a file called ‘unformatted.json’. To make a JSON string human readable open up the Terminal on your Mac 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

Pretty printing a JSON file with VIM and Python:

:%!python -m json.tool

If you don’t have Python installed, then you can also use a web-based service to make the JSON strings human readable.

In case you are using Firefox to send the HTTP request and need to see the response in human readable JSON in the browser itself, then you should use the JSONView Firefox Addon. Similarly on Google Chrome, you can use the JSON Formatter Extension

Print XML in Human Readable Form

Likewise when you want to pretty print XML in human readable form on OSX, then type in:

cat unformatted.xml | xmllint --format - > formatted.xml
pbpaste | xmllint --format - > formatted.xml

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


Leave a Reply

Your email address will not be published. Required fields are marked *

CommentLuv badge