S
S
source20032016-12-07 10:51:36
Computer networks
source2003, 2016-12-07 10:51:36

Why does the Unexpected token in JSON error occur very often?

Unexpected token : in JSON at position 2539.
Positions are always different, characters are also different.
The bottom line is that a script is running that very often accesses the Api of one site, and such an error occurs in about 5% of requests, and if you send exactly the same request again, there will be no error.

var options = {
                    host: 'example.com',
                    path: '/path'
                };

                var request = http.get(options, function(res) {
                    let rawData = '';
                    res.on('data', (chunk) => rawData += chunk);
                    res.on('end', () => {
                        try {
                            let parsedData = JSON.parse(rawData);
                        } catch (e) {
                            console.log(e.message);
                        }
                    });
                });

Error, caught in catch(e)

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexander Wolf, 2016-12-07
@mannaro

Not valid JSON is returned.

L
Lynn "Coffee Man", 2016-12-07
@Lynn

More or less like this

var request = http.get(options, function(res) {
                    let rawData = [];
                    res.on('data', (chunk) => rawData.push(chunk));
                    res.on('end', () => {
                        rawData = Buffer.concat(rawData).toString();
                        try {
                            let parsedData = JSON.parse(rawData);
                        } catch (e) {
                            console.log(e.message);
                        }
                    });
                });

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question