Skip to content

Instantly share code, notes, and snippets.

@acalism
Last active February 1, 2016 07:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save acalism/e486a4316129200f4abd to your computer and use it in GitHub Desktop.
Save acalism/e486a4316129200f4abd to your computer and use it in GitHub Desktop.
XML 和 JSON 在命令行下的可读性
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!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment