— print formatted JSON, XML from MacOS command line

Working with various interfaces that output json or xml results in lots of situations where you have a single-line, unformatted output. Here’s a quick way to format json, xml from the CLI using Python or jq.

via the command line:

format json

Python: cat unformatted.json | python -m json.tool

jq: cat unformatted.json | jq .

format json from clipboard (MacOS)

Python: pbpaste | python -m json.tool

jq: pbpaste | jq.

format xml

from clipboard: pbpaste | xmllint --format -

xmllint is part of libxml2 and installed by default on OSX. Be aware that xmllint cleans up XML as well as formatting it, ocassionally modifying the output.

for all above examples, you can pipe back to the clipboard with | pbcopy at the end of the command, or output to a file with > output.json or > output.xml.