0

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!

1
  • You're trying to parse the string as soon as you get some data (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? Commented Mar 28, 2015 at 16:01

1 Answer 1

1

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);
    });
  }
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.