javascript – SyntaxError: Unexpected token o in JSON at position 1

javascript – SyntaxError: Unexpected token o in JSON at position 1

The JSON you posted looks fine, however in your code, it is most likely not a JSON string anymore, but already a JavaScript object. This means, no more parsing is necessary.

You can test this yourself, e.g. in Chromes console:

new Object().toString()
// [object Object]

JSON.parse(new Object())
// Uncaught SyntaxError: Unexpected token o in JSON at position 1

JSON.parse([object Object])
// Uncaught SyntaxError: Unexpected token o in JSON at position 1

JSON.parse() converts the input into a string. The toString() method of JavaScript objects by default returns [object Object], resulting in the observed behavior.

Try the following instead:

var newData = userData.data.userList;

The first parameter of the JSON.parse function is expected to be a string, and your data is a JavaScript object, so it will coerce it to the string [object Object]. You should use JSON.stringify before passing the data:

JSON.parse(JSON.stringify(userData))

javascript – SyntaxError: Unexpected token o in JSON at position 1

Dont ever use JSON.parse without wrapping it in try-catch block:

// payload 
let userData = null;

try {
    // Parse a JSON
    userData = JSON.parse(payload); 
} catch (e) {
    // You can read e for more info
    // Lets assume the error is that we already have parsed the payload
    // So just return that
    userData = payload;
}

// Now userData is the parsed result

Leave a Reply

Your email address will not be published.