Formatting from console

Working on MacOS, I often find tools that will spew out JSON or XML and I then find myself trying to understand what they're up to.

Clipboard

For starters, if you don't have a clean stream or file, you can often get by with copying the text to the clipboard.

When you do that, pbpaste comes to the rescue. Simply run something like pbpaste | my-tool and you're off to the races.

JSON

jq is your friend here, although I have discussed python tools and scripts to do this as well.

A simple pbpaste | jq . will typically do the trick.

XML

xmllint is your friend here.

pbpaste | xmllint --format - will have the XML linter format the standard input, and that should make it substantially easier to work with.

To zero in on specifics, you can do something like grep of course, but to get good XML output in case you need to pipe or visualize, you can use xsltproc with xsltproc my.xslt my.xml or something along those lines. You might need to write your output to a temporary file to do the xslt processing (certainly the stylesheet will be handy to have this way).

If you just want to remove elements to clean up noise, you could do something like this.

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
                xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                xmlns="http://www.w3.org/1999/xhtml">
<xsl:output method="xml"
            version="1.0"
            encoding="UTF-8"
            indent="yes"/>

<!-- suppress certain attributes if they're empty -->
<xsl:template match="@foo">
  <xsl:if test=".!=''">
    <xsl:copy-of select = '.' />
  </xsl:if>
</xsl:template>

<!-- suppress elements/subtrees we don't care about -->
<xsl:template match="noise">
</xsl:template>

<!-- pass / evaluate everything else -->
<xsl:template match="node() | @*">
    <xsl:copy>
        <xsl:apply-templates select="node() | @*"/>
    </xsl:copy>
</xsl:template>

</xsl:stylesheet>

If you still want a fancier visualization, a cheap way to do so would be to write to disk and run open -a "Google Chrome" my.xml updating to the correct file.

Happy formatting!

Tags:  xmlxslt

Home