How to Solve JS error: Unexpected end of JSON input,Unexpected token u in JSON at position 0

js error Unexpected end of JSON input, Unexpected token u in JSON at position 0

JSON is usually used to exchange data with the server.

When receiving server data, it is generally a character string.

We can use the JSON.parse() method to convert the data into JavaScript objects.

Try the returned results of these kinds of parameters in the Console debugging platform of Google Chrome:

JSON.parse( null );
 // null 

JSON.parse( "" );
 // VM6600:1 Uncaught SyntaxError: Unexpected end of JSON input

JSON.parse(undefined);
// VM6635:1 Uncaught SyntaxError: Unexpected token u in JSON at position 0

It can be found that the parameters of JSON.parse() must conform to the format of the JSON string to be correctly converted into objects, otherwise it may cause errors and affect other codes.

When we are not sure about the type of data returned by the server, these few examples can be used:

// Judging whether the data exists 
var str = str && JSON.parse(str) || {};

// Judging the data type 
var str = typeof str == "string"? JSON.parse(str): {};

// Catch exceptions by try catch to prevent the code from reporting errors 
var c = null ;
 try {
    c = JSON.parse(str)
} catch (d) {}

The same is true for JSON.stringify

var g = "" ;
 try {
    g = JSON.stringify(a)
} catch (u) {}

"object" == typeof a? JSON.stringify(a): a

Read More:

Leave a Reply

Your email address will not be published. Required fields are marked *