0

My Node.js application reads a string, containing JSON data, from a Python backend using GET method. Sometimes when I use JSON.parse() and refresh the page after it succeeds, it gives an Unexpected token , error.

[
      {
       "postid":"c4jgud85mhs658sg4hn94jmd75s67w8r",
       "email":"[email protected]",
       "post":"hello world",
       "comment":[]
      },
      {
       "postid":"c4jgud85mhs658sg4hn94jmd75s67w8r",
       "email":"[email protected]",
       "post":"hello world",
       "comment":[]
      }
]

By console.logging the JSON object, I was able to verify that it only prints the object partially (meaning that only a part of the object was passed) when it gives the error - for example:

4hn94jmd75s67w8r",
       "email":"[email protected]",
       "post":"hello world",
       "comment":[]
      }
]

or

[
      {
       "postid":"c4jgud85mhs658sg

In node.js, Im only using

var data = JSON.parse(resJSON); //resJSON is the variable containing the JSON

8
  • That might be because the JSON is invalid: jsonlint.com Commented Oct 20, 2014 at 1:00
  • I've checked my json file in the browser..its valid Commented Oct 20, 2014 at 1:02
  • You're missing a double quote at the end of comment in the first object. Commented Oct 20, 2014 at 1:04
  • Can you share the Node.js code that handles the response of the GET request? Commented Oct 20, 2014 at 1:10
  • Please share relevant code, as well as the full error message; "Invalid token" must precede something like "expected xx instead of yy" Commented Oct 20, 2014 at 1:12

1 Answer 1

3

If it's succeeding "sometimes," I'd suspect you're parsing the response as the 'data' arrives, such as:

http.get('...', function (res) {
    res.on('data', function (data) {
        console.log(JSON.parse(data.toString()));
    });
});

This will work if the response is sent all at once. But, it can also be divided into multiple chunks that will be received through multiple 'data' events.

To handle chunked responses, you'll want to combine the chunks back together and parse the response as a whole once the stream has come to an 'end'.

http.get('...', function (res) {
    var body = '';

    res.on('data', function (chunk) {
        body += chunk.toString();
    });

    res.on('end', function () {
        console.log(JSON.parse(body));
    });
});
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.