Tag Archives: JSON parse error

[Solved] JSON.parse() Error: Unexpected end of JSON input

Error returned during JSON.parse() conversion due to conversion characters or other special characters in the data of the converted JSON.stringify().

Solution:

encoding before the JSON.stringify() transformation and decoding the operation when JSON.parse() is solved.

Example:

Jump pass parameter

 toEdit() {
    this.data.userInfo.faceData = this.data.faceData
    let info = encodeURIComponent(JSON.stringify(this.data.userInfo))
    wx.navigateTo({
      url: '../userEdit/userEdit?info=' + info 
    })
  },

receive data

onLoad(options) {
	//decodeURIComponent decoding
   let info = JSON.parse(decodeURIComponent(options.info))
   this.setData({info:info})
}

Json.parse: All Error & How to Solve Them

Error Messages:
Uncaught SyntaxError: Unexpected token N in JSON at position 0

JSON.parse(NaN)
JSON.parse('NaN')

Error Messages:
Uncaught SyntaxError: Unexpected token u in JSON at position 0

JSON.parse(undefind)
JSON.parse('undefind')

Error Messages:
Uncaught SyntaxError: Unexpected token o in JSON at position 1

JSON.parse({a:2})

Error Messages:
Uncaught SyntaxError: Unexpected token a in JSON at position 1

JSON.parse('{a:2}')

Error Messages:
Unexpected token ' in JSON at position 1

JSON.parse("{'a':11}")

Error Messages:

JSON.parse('{"a":11}'

**About json.parse

JSON.parseFor parsing JSON string, and returns the corresponding value, which parameters must conform to the format JSON string, otherwise an error.
JSON Is a syntax used to serialize objects, arrays, numbers, strings, Boolean values, and null.
JSON The attribute names of objects and arrays must be strings enclosed in double quotes, and there must be no comma after the last attribute.
JSON The string should also be enclosed in double quotes.
JSON values are forbidden to have leading zeros (JSON.stringify method automatically ignore leading zeros, and the JSON.parse method will report error); if there is a decimal point, then followed by at least one digit.

[Solved] JSON parse error: Unexpected character (‘‘‘ (code 39)): was expecting double-quote to start ……

This problem is encountered in spring MVC and JSP simulating asynchronous requests of Ajax.

Complete error message:

JSON parse error: Unexpected character (''' (code 39)): was expecting double-quote to start field name; nested exception is com.fasterxml.jackson.core.JsonParseException: Unexpected character (''' (code 39)): was expecting double-quote to start field name

Error reason: the format of JSON in the front-end Ajax request is incorrect. The outer part of the array should be wrapped in single quotation marks, and the inner key & amp; Value pairs are enclosed in double quotes.

As shown below.

           $.ajax(
                {
                    url:"testAjax",
                    contentType:"application/json;charset=UTF-8",
                    //Right
                    data:'{"username":"zs","password":"12456","age":"18"}',
                    //Wrong
                    data:"{'username':'zs','password':'12456','age':'18'}",
                    dataType:"json",
                    type:"post",
                    success:function (data) {
                    //    data is the server-side response data
                        alert(data);
                        alert(data.username)
                    }
                }

[Solved] Interface automation test: JSON parse error

1.error:
{
“title” : “Bad Request”,
“status” : 400,
“detail” : “JSON parse error: Unrecognized token ‘username’: was expecting (‘true’, ‘false’ or ‘null’); nested exception is com.fasterxml.jackson.core.JsonParseException: Unrecognized token ‘username’: was expecting (‘true’, ‘false’ or ‘null’)\n at [Source: (PushbackInputStream); line: 1, column: 10]”,
“path” : “/getToken”,
“message” : “error.http.400”
}
2.codes

import requests


url = 'http://10.165.153.210/getToken'
headers = {
    'Content-Type': 'application/json'
}
payload = {
    'username': 'pad_view',
    'password': '6368da1213cd4c4538128a0e9acd0288'
}
res = requests.post(url=url,method='post', data=payload, headers=headers)
print(res.text)

3. Reasons

When you request to pass parameters, the JSON string and dictionary look the same, but the background serialization format is different. Therefore, a JSON parsing error will be reported when data is passed in

4. Solutions

Convert dictionary object to JSON string

4.1 import JSON

import json

4.2 convert dictionary object to JSON string

payload = json.dumps({
    'username': 'username',
    'password': 'password'
})

4.3 complete modification code, as follows

import requests
import json  # import json


url = 'http://10.165.153.210/getToken'
headers = {
    'Content-Type': 'application/json'
}
# Convert a dictionary object into a json string, using the json.dumps() method
payload = json.dumps({
    'username': 'pad_view',
    'password': '6368da1213cd4c4538128a0e9acd0288'
})
res = requests.post(url=url,method='post', data=payload, headers=headers)
# Print the response message
print(res.text)

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

JSON parse error: raw timestamp (1595952000000) not allowed for

The solution is to add a local DataTime serialized configuration class, which will be transferred again when accepted

@Configuration
public class LocalDateTimeSerializerConfig {

    @Bean
    public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() {
        return builder -> {
            builder.serializerByType(LocalDateTime.class, new LocalDateTimeSerializer());
            builder.deserializerByType(LocalDateTime.class, new LocalDateTimeDeserializer());
        };
    }

    /**
     * Serialization
     */
    public static class LocalDateTimeSerializer extends JsonSerializer<LocalDateTime> {
        @Override
        public void serialize(LocalDateTime value, JsonGenerator gen, SerializerProvider serializers)
                throws IOException {
            if (value != null) {
                long timestamp = value.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
                gen.writeNumber(timestamp);
            }
        }
    }

    /**
     *Deserialization
     */
    public static class LocalDateTimeDeserializer extends JsonDeserializer<LocalDateTime> {
        @Override
        public LocalDateTime deserialize(JsonParser p, DeserializationContext deserializationContext)
                throws IOException {
            long timestamp = p.getValueAsLong();
            if (timestamp > 0) {
                return LocalDateTime.ofInstant(Instant.ofEpochMilli(timestamp), ZoneId.systemDefault());
            } else {
                return null;
            }
        }
    }
}

JSON parse error: Can not deserialize instance of java.lang.String out of START_OBJECT token

The problem
After the front end passes JSON format data to the back end, SpringMVC reports

org.springframework.http.converter.HttpMessageNotReadableException:
     * JSON parse error: Can not deserialize instance of java.lang.String out of START_OBJECT token;
     * nested exception is com.fasterxml.jackson.databind.JsonMappingException:
     * Can not deserialize instance of java.lang.String out of START_OBJECT token
     *  at [Source: java.io.PushbackInputStream@6822f8aa; line: 1, column: 88] (through reference chain: com.xxx.XXXDto["employees"])

plan
To solve this problem, we can use one of the Uniform Exception Handling methods in Spring

@ExceptionHandler({HttpMessageNotReadableException.class, JsonMappingException.class, HttpMediaTypeNotSupportedException.class})
    @ResponseBody
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Map<String,Object> exceptionHandler(Exception ex){
        Map<String,Object> map = new HashMap<>(3);
        try{
           map.put("code","400");
           map.put("msg",ex.getMessage());
           return map;
        }catch (Exception e){
            log.error("exception handler error",e);
            map.put("code","400");
            map.put("msg",e.getMessage());
            return map;
        }
    }

Solve problems encountered in the process
The above method can handle the problem of JSON formatting errors, but the data content returned to the front end is in the following format

JSON parse error: Can not deserialize instance of java.lang.String out of START_OBJECT token;  nested exception is com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.lang.String out of START_OBJECT token  at [Source: java.io.PushbackInputStream@6822f8aa; line: 1, column: 88] (through reference chain: com.xxx.XXXDto["callBackUrl"])

We can’t see what the problem is at first sight, and even if we are familiar with the error, we can’t immediately find out where the problem is, because we need to process the above data and then send it back to the front end. Right
Finally solve the problem
We debug the source code found, Change is abnormal in springframework org. Springframework. HTTP. Converter. Json. AbstractJackson2HttpMessageConverter
thrown inside abnormal is
JsonMappingException extends JsonProcessingException
, Thrown in for springmvc HttpMessageNotReadableException, as a result, we only need to add corresponding processing logic unified exception handling, can be returned to the front

@ExceptionHandler({HttpMessageNotReadableException.class, JsonMappingException.class, HttpMediaTypeNotSupportedException.class})
    @ResponseBody
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Map<String,Object> exceptionHandler(Exception ex){
        Map<String,Object> map = new HashMap<>(3);
        try{
            if(ex instanceof HttpMessageNotReadableException
                    && ex.getMessage().indexOf("JSON parse error:")>-1){
                map.put("code","400");
                String message=ex.getMessage();
                int beginIndex=message.indexOf("XXXDto[\"");
                int endIndex=message.indexOf("\"])",beginIndex);
                message="parameter"+message.substring(beginIndex+22,endIndex)+" format error";
                map.put("msg",message);
            }else{
                map.put("code","400");
                map.put("msg",ex.getMessage());
            }
            return map;
        }catch (Exception e){
            log.error("exception handler error",e);
            map.put("code","400");
            map.put("msg",e.getMessage());
            return map;
        }
    }