Chaitanya Govande
Chaitanya Govande

Reputation: 1

Unable to parse JSON string to object

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!

Upvotes: 0

Views: 176

Answers (1)

mscdex
mscdex

Reputation: 106698

You're not buffering the whole contents before parsing. data is emitted for a single chunk, which may or may not be the entire response.

Try this:

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

Upvotes: 1

Related Questions