Recently I’ve been running into problems trying to save JSON in the MySQL database. Even though MySQL supports JSON type for a while 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 of 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 straightforward solution in the form of a built-in JS function.
So this is the list of the forbidden (invalid) characters that will break your JSON:
- form feed
- carriage return
- double quote
You can escape these forbidden (invalid) characters with the following:
To be sure that you’ve properly escaped the strings in your JSON, you could also use JSON.stringify() function and then String.replace().