How to Parse XML Response to JSON in Node.js

One of the coding puzzles for a client I had is to parse XML response to JSON in Node.js.  Let’s see a quick sample solution here which worked for me.

1. Getting the response.

For this example, let’s a yahoo weather xml API for getting the XML response.  And we will use this to see how to parse XML response to JSON in Node.js.  We will use the get function of https object.

https.get('url', (resp) => {
// your code here
});

2.  Parsing XML to JSON

A module named xml2js comes to our rescue here. Install the module in your node.js project:

npm install xml2js

and can be used in your code as follows:

var parseString = require('xml2js').parseString;
...
parseString(data, function (err, result) {
    ...
    console.log(JSON.stringify(result));
});
...

3. Summing it up

Let’s see the whole code in action:

const https = require('https');
var parseString = require('xml2js').parseString;

https.get('https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20woeid%20in%20(select%20woeid%20from%20geo.places(1)%20where%20text%3D%22surat%22)&format=xml&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys', (resp) => {
    let data = '';

    // A chunk of data has been recieved.
    resp.on('data', (chunk) => {
        data += chunk;
    });

    // The whole response has been received. Print out the result.
    resp.on('end', () => {
        //console.log(JSON.parse(data).explanation);

        parseString(data, function (err, result) {
            console.log(JSON.stringify(result));
        });
    });

}).on("error", (err) => {
    console.log("Error: " + err.message);
});

The XML  response for this url is as follows:

<?xml version="1.0" encoding="UTF-8"?>
<query xmlns:yahoo="http://www.yahooapis.com/v1/base.rng"
    yahoo:count="1" yahoo:created="2017-11-16T12:06:42Z" yahoo:lang="en-US">
    <results>
        <channel>
            <yweather:units
                xmlns:yweather="http://xml.weather.yahoo.com/ns/rss/1.0"
                distance="mi" pressure="in" speed="mph" temperature="F"/>
            <title>Yahoo! Weather - Surat, GJ, IN</title>
            <link>http://us.rd.yahoo.com/dailynews/rss/weather/Country__Country/*https://weather.yahoo.com/country/state/city-2295405/</link>
            <description>Yahoo! Weather for Surat, GJ, IN</description>
            <language>en-us</language>
            <lastBuildDate>Thu, 16 Nov 2017 05:36 PM IST</lastBuildDate>
            <ttl>60</ttl>
            <yweather:location
                xmlns:yweather="http://xml.weather.yahoo.com/ns/rss/1.0"
                city="Surat" country="India" region=" GJ"/>
            <yweather:wind
                xmlns:yweather="http://xml.weather.yahoo.com/ns/rss/1.0"
                chill="84" direction="338" speed="14"/>
            <yweather:atmosphere
                xmlns:yweather="http://xml.weather.yahoo.com/ns/rss/1.0"
                humidity="30" pressure="1008.0" rising="0" visibility="16.1"/>
            <yweather:astronomy
                xmlns:yweather="http://xml.weather.yahoo.com/ns/rss/1.0"
                sunrise="6:50 am" sunset="5:57 pm"/>
            <image>
                <title>Yahoo! Weather</title>
                <width>142</width>
                <height>18</height>
                <link>http://weather.yahoo.com</link>
                <url>http://l.yimg.com/a/i/brand/purplelogo//uh/us/news-wea.gif</url>
            </image>
            <item>
                <title>Conditions for Surat, GJ, IN at 04:30 PM IST</title>
                <geo:lat xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#">21.17642</geo:lat>
                <geo:long xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#">72.814087</geo:long>
                <link>http://us.rd.yahoo.com/dailynews/rss/weather/Country__Country/*https://weather.yahoo.com/country/state/city-2295405/</link>
                <pubDate>Thu, 16 Nov 2017 04:30 PM IST</pubDate>
                <yweather:condition
                    xmlns:yweather="http://xml.weather.yahoo.com/ns/rss/1.0"
                    code="32" date="Thu, 16 Nov 2017 04:30 PM IST"
                    temp="85" text="Sunny"/>
                <yweather:forecast
                    xmlns:yweather="http://xml.weather.yahoo.com/ns/rss/1.0"
                    code="32" date="16 Nov 2017" day="Thu" high="89"
                    low="69" text="Sunny"/>
                <yweather:forecast
                    xmlns:yweather="http://xml.weather.yahoo.com/ns/rss/1.0"
                    code="32" date="17 Nov 2017" day="Fri" high="88"
                    low="69" text="Sunny"/>
                <yweather:forecast
                    xmlns:yweather="http://xml.weather.yahoo.com/ns/rss/1.0"
                    code="34" date="18 Nov 2017" day="Sat" high="87"
                    low="71" text="Mostly Sunny"/>
                <yweather:forecast
                    xmlns:yweather="http://xml.weather.yahoo.com/ns/rss/1.0"
                    code="30" date="19 Nov 2017" day="Sun" high="88"
                    low="71" text="Partly Cloudy"/>
                <yweather:forecast
                    xmlns:yweather="http://xml.weather.yahoo.com/ns/rss/1.0"
                    code="30" date="20 Nov 2017" day="Mon" high="88"
                    low="73" text="Partly Cloudy"/>
                <yweather:forecast
                    xmlns:yweather="http://xml.weather.yahoo.com/ns/rss/1.0"
                    code="30" date="21 Nov 2017" day="Tue" high="91"
                    low="73" text="Partly Cloudy"/>
                <yweather:forecast
                    xmlns:yweather="http://xml.weather.yahoo.com/ns/rss/1.0"
                    code="32" date="22 Nov 2017" day="Wed" high="90"
                    low="74" text="Sunny"/>
                <yweather:forecast
                    xmlns:yweather="http://xml.weather.yahoo.com/ns/rss/1.0"
                    code="32" date="23 Nov 2017" day="Thu" high="90"
                    low="72" text="Sunny"/>
                <yweather:forecast
                    xmlns:yweather="http://xml.weather.yahoo.com/ns/rss/1.0"
                    code="32" date="24 Nov 2017" day="Fri" high="87"
                    low="70" text="Sunny"/>
                <yweather:forecast
                    xmlns:yweather="http://xml.weather.yahoo.com/ns/rss/1.0"
                    code="32" date="25 Nov 2017" day="Sat" high="84"
                    low="63" text="Sunny"/>
                <description>&lt;![CDATA[&lt;img src="http://l.yimg.com/a/i/us/we/52/32.gif"/&gt;
&lt;BR /&gt;
&lt;b&gt;Current Conditions:&lt;/b&gt;
&lt;BR /&gt;Sunny
&lt;BR /&gt;
&lt;BR /&gt;
&lt;b&gt;Forecast:&lt;/b&gt;
&lt;BR /&gt; Thu - Sunny. High: 89Low: 69
&lt;BR /&gt; Fri - Sunny. High: 88Low: 69
&lt;BR /&gt; Sat - Mostly Sunny. High: 87Low: 71
&lt;BR /&gt; Sun - Partly Cloudy. High: 88Low: 71
&lt;BR /&gt; Mon - Partly Cloudy. High: 88Low: 73
&lt;BR /&gt;
&lt;BR /&gt;
&lt;a href="http://us.rd.yahoo.com/dailynews/rss/weather/Country__Country/*https://weather.yahoo.com/country/state/city-2295405/"&gt;Full Forecast at Yahoo! Weather&lt;/a&gt;
&lt;BR /&gt;
&lt;BR /&gt;
&lt;BR /&gt;
]]&gt;</description>
                <guid isPermaLink="false"/>
            </item>
        </channel>
    </results>
</query>

And the converted JSON  for the same by the above code is as follows:

{
   "query":{
      "$":{
         "xmlns:yahoo":"http://www.yahooapis.com/v1/base.rng",
         "yahoo:count":"1",
         "yahoo:created":"2017-11-16T12:16:47Z",
         "yahoo:lang":"en-US"
      },
      "results":[
         {
            "channel":[
               {
                  "yweather:units":[
                     {
                        "$":{
                           "xmlns:yweather":"http://xml.weather.yahoo.com/ns/rss/1.0",
                           "distance":"mi",
                           "pressure":"in",
                           "speed":"mph",
                           "temperature":"F"
                        }
                     }
                  ],
                  "title":[
                     "Yahoo! Weather - Surat, GJ, IN"
                  ],
                  "link":[
                     "http://us.rd.yahoo.com/dailynews/rss/weather/Country__Country/*https://weather.yahoo.com/country/state/city-2295405/"
                  ],
                  "description":[
                     "Yahoo! Weather for Surat, GJ, IN"
                  ],
                  "language":[
                     "en-us"
                  ],
                  "lastBuildDate":[
                     "Thu, 16 Nov 2017 05:46 PM IST"
                  ],
                  "ttl":[
                     "60"
                  ],
                  "yweather:location":[
                     {
                        "$":{
                           "xmlns:yweather":"http://xml.weather.yahoo.com/ns/rss/1.0",
                           "city":"Surat",
                           "country":"India",
                           "region":" GJ"
                        }
                     }
                  ],
                  "yweather:wind":[
                     {
                        "$":{
                           "xmlns:yweather":"http://xml.weather.yahoo.com/ns/rss/1.0",
                           "chill":"84",
                           "direction":"338",
                           "speed":"14"
                        }
                     }
                  ],
                  "yweather:atmosphere":[
                     {
                        "$":{
                           "xmlns:yweather":"http://xml.weather.yahoo.com/ns/rss/1.0",
                           "humidity":"30",
                           "pressure":"1008.0",
                           "rising":"0",
                           "visibility":"16.1"
                        }
                     }
                  ],
                  "yweather:astronomy":[
                     {
                        "$":{
                           "xmlns:yweather":"http://xml.weather.yahoo.com/ns/rss/1.0",
                           "sunrise":"6:50 am",
                           "sunset":"5:57 pm"
                        }
                     }
                  ],
                  "image":[
                     {
                        "title":[
                           "Yahoo! Weather"
                        ],
                        "width":[
                           "142"
                        ],
                        "height":[
                           "18"
                        ],
                        "link":[
                           "http://weather.yahoo.com"
                        ],
                        "url":[
                           "http://l.yimg.com/a/i/brand/purplelogo//uh/us/news-wea.gif"
                        ]
                     }
                  ],
                  "item":[
                     {
                        "title":[
                           "Conditions for Surat, GJ, IN at 04:30 PM IST"
                        ],
                        "geo:lat":[
                           {
                              "_":"21.17642",
                              "$":{
                                 "xmlns:geo":"http://www.w3.org/2003/01/geo/wgs84_pos#"
                              }
                           }
                        ],
                        "geo:long":[
                           {
                              "_":"72.814087",
                              "$":{
                                 "xmlns:geo":"http://www.w3.org/2003/01/geo/wgs84_pos#"
                              }
                           }
                        ],
                        "link":[
                           "http://us.rd.yahoo.com/dailynews/rss/weather/Country__Country/*https://weather.yahoo.com/country/state/city-2295405/"
                        ],
                        "pubDate":[
                           "Thu, 16 Nov 2017 04:30 PM IST"
                        ],
                        "yweather:condition":[
                           {
                              "$":{
                                 "xmlns:yweather":"http://xml.weather.yahoo.com/ns/rss/1.0",
                                 "code":"32",
                                 "date":"Thu, 16 Nov 2017 04:30 PM IST",
                                 "temp":"85",
                                 "text":"Sunny"
                              }
                           }
                        ],
                        "yweather:forecast":[
                           {
                              "$":{
                                 "xmlns:yweather":"http://xml.weather.yahoo.com/ns/rss/1.0",
                                 "code":"32",
                                 "date":"16 Nov 2017",
                                 "day":"Thu",
                                 "high":"89",
                                 "low":"69",
                                 "text":"Sunny"
                              }
                           },
                           {
                              "$":{
                                 "xmlns:yweather":"http://xml.weather.yahoo.com/ns/rss/1.0",
                                 "code":"32",
                                 "date":"17 Nov 2017",
                                 "day":"Fri",
                                 "high":"88",
                                 "low":"69",
                                 "text":"Sunny"
                              }
                           },
                           {
                              "$":{
                                 "xmlns:yweather":"http://xml.weather.yahoo.com/ns/rss/1.0",
                                 "code":"34",
                                 "date":"18 Nov 2017",
                                 "day":"Sat",
                                 "high":"87",
                                 "low":"71",
                                 "text":"Mostly Sunny"
                              }
                           },
                           {
                              "$":{
                                 "xmlns:yweather":"http://xml.weather.yahoo.com/ns/rss/1.0",
                                 "code":"30",
                                 "date":"19 Nov 2017",
                                 "day":"Sun",
                                 "high":"88",
                                 "low":"71",
                                 "text":"Partly Cloudy"
                              }
                           },
                           {
                              "$":{
                                 "xmlns:yweather":"http://xml.weather.yahoo.com/ns/rss/1.0",
                                 "code":"30",
                                 "date":"20 Nov 2017",
                                 "day":"Mon",
                                 "high":"88",
                                 "low":"73",
                                 "text":"Partly Cloudy"
                              }
                           },
                           {
                              "$":{
                                 "xmlns:yweather":"http://xml.weather.yahoo.com/ns/rss/1.0",
                                 "code":"30",
                                 "date":"21 Nov 2017",
                                 "day":"Tue",
                                 "high":"91",
                                 "low":"73",
                                 "text":"Partly Cloudy"
                              }
                           },
                           {
                              "$":{
                                 "xmlns:yweather":"http://xml.weather.yahoo.com/ns/rss/1.0",
                                 "code":"32",
                                 "date":"22 Nov 2017",
                                 "day":"Wed",
                                 "high":"90",
                                 "low":"74",
                                 "text":"Sunny"
                              }
                           },
                           {
                              "$":{
                                 "xmlns:yweather":"http://xml.weather.yahoo.com/ns/rss/1.0",
                                 "code":"32",
                                 "date":"23 Nov 2017",
                                 "day":"Thu",
                                 "high":"90",
                                 "low":"72",
                                 "text":"Sunny"
                              }
                           },
                           {
                              "$":{
                                 "xmlns:yweather":"http://xml.weather.yahoo.com/ns/rss/1.0",
                                 "code":"32",
                                 "date":"24 Nov 2017",
                                 "day":"Fri",
                                 "high":"87",
                                 "low":"70",
                                 "text":"Sunny"
                              }
                           },
                           {
                              "$":{
                                 "xmlns:yweather":"http://xml.weather.yahoo.com/ns/rss/1.0",
                                 "code":"32",
                                 "date":"25 Nov 2017",
                                 "day":"Sat",
                                 "high":"84",
                                 "low":"63",
                                 "text":"Sunny"
                              }
                           }
                        ],
                        "description":[
                           "<![CDATA[<img src=\"http://l.yimg.com/a/i/us/we/52/32.gif\"/>\n<BR />\n<b>Current Conditions:</b>\n<BR />Sunny\n<BR />\n<BR />\n<b>Forecast:</b>\n<BR /> Thu - Sunny. High: 89Low: 69\n<BR /> Fri - Sunny. High: 88Low: 69\n<BR /> Sat - Mostly Sunny. High: 87Low: 71\n<BR /> Sun - Partly Cloudy. High: 88Low: 71\n<BR /> Mon - Partly Cloudy. High: 88Low: 73\n<BR />\n<BR />\n<a href=\"http://us.rd.yahoo.com/dailynews/rss/weather/Country__Country/*https://weather.yahoo.com/country/state/city-2295405/\">Full Forecast at Yahoo! Weather</a>\n<BR />\n<BR />\n<BR />\n]]>"
                        ],
                        "guid":[
                           {
                              "$":{
                                 "isPermaLink":"false"
                              }
                           }
                        ]
                     }
                  ]
               }
            ]
         }
      ]
   }
}

Feel free to look at the GitHub code for the above example.

4. Conclusion

In this short article we were able to explore how to fetch XML response from web service and convert it into a JSON object.