Developing software in the Real World

Pretty print curl -i

My favourite tool for working with APIs is curl and in particular, I like using the -I switch to view the status line and headers too:

This generates an output that looks like this:

What I would like to do is pretty print the body if it's JSON or XML so that it's easier to read. There are some tools out there, like jq which will format JSON, but they can't seem to cope if the first part of the string is not JSON:

Solution 1: Use -D flag

The easiest solution is to use the -D flag to send the headers to stderr:

To make this easier, you can add to your ~/.curlrc. Mine looks like this:

Now you never need to think about it.

Solution 2: A simple script to pipe the output through

Another way to do it is via a script that knows where the body starts. We can write this in PHP and it can automatically pretty print XML for us too:

Save this as as /usr/local/prettyprint, make it executable with chmod a+w /usr/bin/prettyprint and you're good to go:

Pick the solution that works best for you!

One thought on “Pretty print curl -i

Leave a Reply

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