Node.js Convert JSON to XML, Pluralize

Support this website by purchasing prints of my photographs! Check them out here.

I've been doing a lot recently with building an API using Node.js. One of the features of the API is that it will provide JSON or XML depending on the accept header passed in by the client. One thing I didn't want each API request to do was handle the logic for building an XML object, since the code is painful and would slow down development. My solution is to use a module which converts a JS object (JSON) into XML.

There are a few existing modules out that that do this, but none of them seem to do it nicely. For example, jstoxml will convert your object, but it handles array items awkwardly. To fix some issues, they recommend nesting attributes deeper, which seems to fix issues. However, I want to have each API call builds a single object and have that converted, and I don't want to send unnecessarily nested JSON.

My goal is to build a converter that makes use of an inflection module to handle singularization / pluralization of attributes. Below you will see the example. If I have an attribute in a JS object which is an array and plural, the children methods should be named the singular version.

{
  "user": "505723c5750c1fa2177682ed",
  "uri": "http://localhost:3000/users/505723c5750c1fa2177682ed/items",
  "items": [
  {
    "_id": 1,
    "uri": "http://localhost:3000/items/1"
  },
  {
    "_id": 2,
    "uri": "http://localhost:3000/items/2"
  }
  ],
  "info": "blah."
}
<result>
    <user>505723c5750c1fa2177682ed</user>
    <uri>http://localhost:3000/users/505723c5750c1fa2177682ed/items</uri>
    <items>
        <item id="1">
            <uri>http://localhost:3000/items/1</uri>
        </item>
        <item id="2">
            <uri>http://localhost:3000/items/2</uri>
        </item>
    </items>
    <info>blah.</info>
</result>

The code I have for my API project uses Express.js. I've added a method to the response object called res.sendData(obj). When that function is invoked, it checks the accept type and determines what kind of data to send back. If it is JSON, it just calls res.send(obj). If it is XML, it will set the header type, call this converter, and send the XML to the browser instead. Thanks to this, each API request function doesn't need to do boilerplate translation or check request type, but if they wanted to they still could do manual work.

Let me know what you think about this, and if you know of any existing modules which follows this same XML serialization method.

Tags: #nodejs #npm #xml
Thomas Hunter II Avatar

Thomas has contributed to dozens of enterprise Node.js services and has worked for a company dedicated to securing Node.js. He has spoken at several conferences on Node.js and JavaScript and is an O'Reilly published author.