![]() |
VOOZH | about |
JSON (JavaScript Object Notation) is a popular data format that is widely used in APIs, configuration files, and data storage. While JSON is straightforward, handling special characters within strings requires some extra care. Certain characters must be escaped to be valid within a JSON string.
Table of Content
The following characters must be escaped in JSON:
Character | Escape Sequence |
|---|---|
" | \" |
\ | \\ |
/ | \/ |
\b | \\b |
\f | \\f |
\n | \\n |
\r | \\r |
\t | \\t |
JavaScript provides native methods for working with JSON, including escaping strings. Let’s start with an example where we manually escape characters within a JSON string.
Example: In this example, the double quotes inside the message are escaped as \". The newline character is represented as \n.
Output:
{
"message": "He said, \"Hello, World!\"\nThis is a new line."
}
If you need to escape a string programmatically (i.e., you're not building a full JSON object but just escaping a string), you can create a helper function to escape special characters.
Example: This function replaces special characters with their escaped equivalents, making the string safe to use in JSON.
Output:
Hello \"World\"!\\nNew line here.Apart from the usual characters like quotes and slashes, there are some other characters you need to handle carefully, especially when dealing with special data. For example, in Unicode, characters need to be escaped if they cannot be represented directly in JSON strings.
Example: In this example, we will use the special characters in JSON strings
Output
{
"unicodeText": "Special char: \u00A9"
}
There are times when you need to unescape strings, especially when retrieving JSON data from external sources that may contain escaped characters.
Example: In this example, we will see the unescaping JSON strings
Output:
He said, "Hello, World!"