Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

node.js and json runtime error

node.js and json runtime error


I am using node.js and trying to parse the JSON body of a request. I am getting the following error:


SyntaxError: Unexpected end of input
    at Object.parse (native)
    at IncomingMessage. (C:\node\xxxx.js:36:14)
    at IncomingMessage.emit (events.js:64:17)
    at HTTPParser.parserOnMessageComplete [as onMessageComplete] (http.js:130:23)
    at Socket.ondata (http.js:1506:22)
    at TCP.onread (net.js:374:27)

I am doing:

     request.on('data', function(chunk)
     // and in the end I am doing
     obj = JSON.parse(data);  // it's complaining at this point.

input is:

    "result": "success",
    "source": "chat"
Problem courtesy of: The Learner


You're trying to parse the data before it is completely recieved...put your JSON.parse inside the .end method of request

var data = '';
request.on('data', function(chunk){
  data += chunk;
request.on('end', function(){
  var obj = JSON.parse(data);
Solution courtesy of: Pastor Bones


View additional discussion.

This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

node.js and json runtime error


Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription