So I am trying to retrieve data from a web server (URL: https://api.uwaterloo.ca/v2/codes/subjects.json?key=6eb0182cf11ca581364ccceee87435f4). I made sure its valid JSON data using JSON validator and it was.
What i am trying to do is get the values of the subject key in the data array. However, when i first try to parse the response as a JSON object, it doesn't let me.
Here is the 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 was saved!");
});
jsonObject = JSON.parse(d);
// console.log(typeof(jsonObject.count));
// for (var key in jsonObject)
// {
// if(jsonObject.hasOwnProperty(key))
// {
// console.log(key + "=" + jsonObject[key]);
// }
// }
});
});
req.end();
req.on('error', function(e) {
console.error(e);
});
I get the following error
^
SyntaxError: Unexpected end of input
at Object.parse (native)
at IncomingMessage.<anonymous> (C:\Users\Chintu\Desktop\Chaitanya\Study\Term
4B\MSCI 444\Project\Full Calendar\Trial\helloworld.js:79:20)
at IncomingMessage.emit (events.js:107:17)
at readableAddChunk (_stream_readable.js:163:16)
at IncomingMessage.Readable.push (_stream_readable.js:126:10)
at HTTPParser.parserOnBody (_http_common.js:132:22)
at TLSSocket.socketOnData (_http_client.js:310:20)
at TLSSocket.emit (events.js:107:17)
at readableAddChunk (_stream_readable.js:163:16)
at TLSSocket.Readable.push (_stream_readable.js:126:10)
Any help is appreciated.
Thank you!
on("data")). Make sure that you have the whole response before you try to parse it. How many times do you get "The file was saved!" in the console?