Node.js Convert JSON to XML, Pluralize
Posted September 21st, 2012 by Thomas Hunter II & filed under Node.js.
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.
Let me know what you think about this, and if you know of any existing modules which follows this same XML serialization method.
Related Posts
Thomas Hunter II
Latest posts by Thomas Hunter II (see all)
- Twitter Plays Zork: @DemocraticZork - 2017-11-26
- Go v1.9.1 vs Node v8.9.0 Microbenchmark - 2017-11-09
- What have I been up to? Late 2017 Edition - 2017-09-28
Nice. What does the API in general do?
I was looking for something like this for NODE â converting Express response from JSON into XML depending on the parameter passed in the URL.
didnât see any code for the API project that you refer to, is that available?
It will be up in a few days here:
Had to get it approved (since itâs a company project).
Nice post. What would be the json format for something like this
string value . In other words how do you represent the object when you want it to have a content as well as attributes?