Aditya Krishnakumar Aditya Krishnakumar - 29 days ago 15
Javascript Question

JSON url parse returns NaN in Node.js

I have created a URL Shortener web service, which returns JSON, if correct parameters (

url
) is passed.

Now, since I am learning Node.js, I am trying to create a Node.js wrapper for parsing the data and printing them in console (for now).

I am using
http
and
request
module for parsing the JSON data which I received from the url response.

This is my code that prints the data :

var request = require('request');
var http = require('http');

var url = process.argv[2];
var apiUrl = "http://shtr.ml/stats-api.php?url=" + url;

http.get(apiUrl,function(res){
var body = '';
res.on('data',function(chunk)
{
body += chunk;
});

res.on('end',function(){
const resp = JSON.parse(body);
console.log(JSON.stringify(resp));
if(resp.message.toString() == "Success")
{
console.log("Short URL : ",resp.short-url);
console.log("Long URL : ",resp.long-url);
console.log("Creation Date : ",resp.created);
console.log("Total Clicks : ",resp.clicks);
}
else
{
console.log("Stats Error !!");
}
});
}).on('error',function(e){
console.log("Got an error ",e);
});


Now, following is my code output :

C:\node-shtr-module>node index.js http://shtr.ml/ZVFWdk


{"message":"Success","short-url":"http://shtr.ml/ZVFWdk","long-url":"https://github.com/beingadityak/dot-net-mysql","created":"2016-09-27 22:58:06","clicks":"21"}

Short URL : NaN
Long URL : NaN
Creation Date : 2016-09-27 22:58:06
Total Clicks : 21


Why is the
resp.short-url
returning
NaN
even though the JSON contains the URL ? Please help.

As always, thanks in advance.

Answer

access it using resp['short-url'] and resp['long-url']

Comments