Invalid characters in JSON

Recently I run into problems trying to save JSON into MySQL database. Even though MySQL supports JSON type for some time now, there are still plenty of gotchas while you work with it. The situation is pretty critical with special characters. This time we are going to be short and on the topic of invalid JSON characters.

When we say invalid we think on characters in JSON strings. Sometimes, the issue can be quite difficult to spot especially for new lines and other nonvisible characters. And there’s no straight-forward solution in the form of built-in JS function.

So this is the list of the forbidden (invalid) characters that will break your JSON: newline, form feed, carriage return, tab, backslash, backspace, and double quote. Those you need to escape like this: \n, \f, \r, \t, \\, \b, \”.

To be sure that the strings in your JSON are properly escaped you could use JSON.stringify() function and then String.replace().

Leave a Reply

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