javascript - Unable to parse JSON string to object -


so trying retrieve data web server (url: https://api.uwaterloo.ca/v2/codes/subjects.json?key=6eb0182cf11ca581364ccceee87435f4). made sure valid json data using json validator , was.

what trying values of subject key in data array. however, when first try parse response json object, doesn't let me.

here code snippet

    var req = https.request('https://api.uwaterloo.ca/v2/codes/subjects.json?key=6eb0182cf11ca581364ccceee87435f4', function(res) {   //res.setencoding('utf8');   res.on('data', function(d) {      //console.log(object.prototype.tostring.call(d));     //jsonstring = json.stringify(d);     //console.log(jsonstring);      fs.writefile("./test.txt", d, function(err) {     if(err) {         return console.log(err);     }      console.log("the file saved!");     });      jsonobject = json.parse(d);      // console.log(typeof(jsonobject.count));      // (var key in jsonobject)     // {         // if(jsonobject.hasownproperty(key))         // {             // console.log(key + "=" + jsonobject[key]);         // }     // }    });  });  req.end();  req.on('error', function(e) {   console.error(e); }); 

i following error

^ syntaxerror: unexpected end of input     @ object.parse (native)     @ incomingmessage.<anonymous> (c:\users\chintu\desktop\chaitanya\study\term  4b\msci 444\project\full calendar\trial\helloworld.js:79:20)     @ incomingmessage.emit (events.js:107:17)     @ readableaddchunk (_stream_readable.js:163:16)     @ incomingmessage.readable.push (_stream_readable.js:126:10)     @ httpparser.parseronbody (_http_common.js:132:22)     @ tlssocket.socketondata (_http_client.js:310:20)     @ tlssocket.emit (events.js:107:17)     @ readableaddchunk (_stream_readable.js:163:16)     @ tlssocket.readable.push (_stream_readable.js:126:10) 

any appreciated.

thank you!

you're not buffering whole contents before parsing. data emitted single chunk, may or may not entire response.

try this:

var req = https.get(url, function(res) {   if (res.statuscode !== 200)     res.resume(); // discard response data   else {     var buf = '';     res.on('data', function(d) {       buf += d;     }).on('end', function() {       var result = json.parse(buf);     });   } }); 

Comments

Popular posts from this blog

google chrome - Developer tools - How to inspect the elements which are added momentarily (by JQuery)? -

angularjs - Showing an empty as first option in select tag -

php - Cloud9 cloud IDE and CakePHP -