简体   繁体   中英

JSON parse gives error occasionally on parsing string

I have same input fields where the user inputs some data. Next my code converts it to JSON and send it to the server.

$("#submit").click(function(){
    var inp = $("#inpTxt").val();

    if(inp == null || inp == ""){
        return;
    }

    jsonResult = JSON.parse('{"data": "' + inp + '"}');

    $.ajax({
        data : jsonResult,
        ...
    });
});

The issue here is that sometimes the above code works and sometimes it just don't. Most of the time I tested the code it worked like a charm but on productions I keep on getting the error reported several times.

I have not been able to figure out the possible cause yet.

Note: Some parts of the code are not shared in above but only part of what the problem seems to be.

As per the last comment the problem seems to be occurring when someone inputs some escape character in input (@Noob46 identified the case of using "Something" case but in my opinion it will also occur if any other escape character like \\ or any other starting with \\ may also cause the same problem).

Thus, one way to handle this is to filter the coming input string before passing it to JSON.parse.

To take things a step forward I have created some js that you can find here which in fact will let you handle the escape characters if they come as part of your input.

For further details refer to the attached code and example in the provided link here .

As the problem identified by me so let me also state an answer here. All you need is to add an additional \\ before all the escape characters you encounter like:

\\b : backspace

\\f : form feed

\\n : line feed

\\r : carriage return

\\t : horizontal tab

\\v : vertical tab " : double quote \\ : back slash

You can do so by code like:

inp = inp.replace('"','\\\"');

Or inp.replace('\\','\\\\\\\\');

And so on for other characters.

When you use JSON.Parse function you need to handle special characters by your self. So if someone puts a " in your inpTxt input it will cause an error on parse that string.

You should do something like the code below to avoid parse error and let javascript correctly handle special characters on your string.

jsonResult = { data: inp };

I create a JS fiddle to make it easier to understand. https://jsfiddle.net/ub3w0a8x/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM