Converting ATOM XML to JSON using Node.js

Post to Twitter

I was reading an article that had some code to convert XML to JSON using Node.js and node-xml2js. The code they used was very simple and since I deal with ATOM XML a lot I wanted to know how well it would work with converting ATOM to JSON.

Note: I’m using Node version 0.6.7

The first thing I did was create a new folder to store the files. Then I added a few Node modules (I installed these locally but feel free to install them globally):

$ npm install xml2js
$ npm install eyes

Note: eyes does a very nice and clean output of values for inspection

The code is borrowed from the original article and modified a little:

var fs = require('fs'),
    eyes = require('eyes'),
    xml2js = require('xml2js');

var parser = new xml2js.Parser();

parser.on('end', function(result) {

fs.readFile(__dirname + '/atom_entry.xml', function(err, data) {

Save the above code as app.js

Create another file called atom_entry.xml and save it to the same folder as the app.js file.

    Atom-Powered Robots Run Amok
    John Doe
    Some text.

Simply run the script and examine the results which will be in JSON:

    content: 'Some text.',
    @: { xmlns: '' },
    id: 'urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a',
    author: { name: 'John Doe' },
    updated: '2003-12-13T18:30:02Z',
    title: 'Atom-Powered Robots Run Amok'

We can throw a little more complex (and borrowed) ATOM XML entry at it as well and you’ll see it does a decent enough job in the translation:

    Atom draft-07 snapshot
        Mark Pilgrim
        Sam Ruby
        Joe Gregorio

[Update: The Atom draft is finished.]

The results:

    author: {
        email: '',
        uri: '',
        name: 'Mark Pilgrim'
    content: {
        div: {
            @: { xmlns: '' },
            p: { i: '[Update: The Atom draft is finished.]' }
        @: {
            type: 'xhtml',
            xml:lang: 'en',
            xml:base: ''
    contributor: [
        { name: 'Sam Ruby' },
        { name: 'Joe Gregorio' }
    updated: '2005-07-31T12:29:29Z',
    link: [
            @: {
                href: '',
                rel: 'alternate',
                type: 'text/html'
            @: {
                href: '',
                length: '1337',
                rel: 'enclosure',
                type: 'audio/mpeg'
    published: '2003-12-13T08:29:29-04:00',
    title: 'Atom draft-07 snapshot',
    id: ',2003:3.2397'

With a little more work you could have a decent system for converting ATOM XML to JSON for a project.

Post to Twitter

This entry was posted in JavaScript, Node.js. Bookmark the permalink.