How to solve JSON.parse: bad control character in string literal, in this code [closed]

The error message is telling you that you have a control character within a string literal, for instance, character code 8 or 10 or 13 or anything below 32 (a space).

The JSON definition tells us that you cannot have literal control characters in string literals, you must use an escape sequence such as \b, \r, \n, or \uXXXX where XXXX is a hex code for a Unicode “code point” (character).

So for instance, pretend the following is in a file (or other data stream):

    "property": "value with an invalid
control character in it"

That’s invalid JSON, the string literal starting with "value has at least one control character in it (the line break, might be one or two control characters depending on the OS).

This is how we would fix it:

    "property": "value with an valid\nescape sequence in it"

Note the \n where the line break used to be.

You can use to validate JSON, it’s quite good at pointing out where the error is.

Re your edit: It is indeed a line break causing the problem:

"distancetot": {
    "map": "function(doc) {var somme= Math.abs(doc.distancet0-    doc.distancet1); if(doc.role=='utilisateur'){ 
Error is here -------------------------------------------------------------------------------------------------^

The line break after if(doc.role=='utilisateur'){ is an invalid control character, just as in my example above.

Leave a Comment