Open In App

How To Escape Strings in JSON?

Last Updated : 03 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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.

JSON Escaping Rules

The following characters must be escaped in JSON:

Character

Escape Sequence

"

\"

\

\\

/

\/

\b

\\b

\f

\\f

\n

\\n

\r

\\r

\t

\\t

Escaping Strings in JavaScript

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.

JavaScript
const jsonString = JSON.stringify({
    message: "He said, \"Hello, World!\"\nThis is a new line."
});

console.log(jsonString);


Output:

{
"message": "He said, \"Hello, World!\"\nThis is a new line."
}

Programmatic Escaping in JavaScript

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.

JavaScript
function escapeString(str) {
    return str
        .replace(/\\/g, '\\\\')   // Escape backslashes
        .replace(/"/g, '\\"')     // Escape double quotes
        .replace(/\n/g, '\\n')    // Escape newlines
        .replace(/\r/g, '\\r')    // Escape carriage returns
        .replace(/\t/g, '\\t');   // Escape tabs
}

const escapedString = escapeString(`Hello "World"!\nNew line here.`);
console.log(escapedString);


Output:

Hello \"World\"!\\nNew line here.

Special Characters in JSON Strings

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

JavaScript
const jsonString = JSON.stringify({
    unicodeText: "Special char: \u00A9"
});

console.log(jsonString);


Output

{
"unicodeText": "Special char: \u00A9"
}

Unescaping JSON Strings

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

JavaScript
const escapedJson = '{"message":"He said, \\"Hello, World!\\""}';
const parsedObject = JSON.parse(escapedJson);

console.log(parsedObject.message);


Output:

He said, "Hello, World!"

Similar Reads