Open In App

How to Add Backslash in JSON String JavaScript ?

Last Updated : 16 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In JavaScript, adding a backslash to a JSON string is important to properly escape special characters, ensuring the integrity and correctness of the JSON format for data processing and storage.

Using JSON.parse() and JSON.stringify()

In this approach, we are using JSON.parse() to convert the JSON string into a JavaScript object, then JSON.stringify() to convert it back to a string with added backslashes using replace() for each double quote, making sure that the JSON string is properly escaped.

Syntax:

JSON.parse(text, reviver)
JSON.stringify(value, replacer, space)

Example: The below example uses JSON.parse() and JSON.stringify() to add a backslash in JSON string JavaScript.

JavaScript
let jStr = 
    `{
        "name": "Geek", 
        "age": 22, 
        "city": "Delhi"
    }`;
let parseJSON = JSON.parse(jStr);
jStr = JSON.stringify(parseJSON).
    replace(/"/g, '\\"');
console.log(jStr);

Output
{\"name\":\"Geek\",\"age\":22,\"city\":\"Delhi\"}

Using for Loop

In this approach, we are using a for loop to iterate through each character in the JSON string jStr, checking for backslashes and double quotes, and appending backslashes where needed to make sure proper escaping of special characters in the resulting res string for correct JSON representation.

Syntax:

for (initialization; condition; increment/decrement) {
// code
}

Example: The below example uses for loop to add backslash in JSON string JavaScript.

JavaScript
let jStr = `{
    "name": "Geek", 
    "age": 22, 
    "city": "Delhi"
}`;
let res = '';
for (let i = 0; i < jStr.length; i++) {
    if (jStr[i] === '\\' || jStr[i] === '"') {
        res += '\\' + jStr[i];
    } else {
        res += jStr[i];
    }
}
console.log(res);

Output
{
    \"name\": \"Geek\", 
    \"age\": 22, 
    \"city\": \"Delhi\"
}

Using Array.prototype.map() and String.prototype.replace()

In this approach, we use Array.prototype.map() to iterate through each character of the JSON string, and String.prototype.replace() to replace double quotes with escaped double quotes, ensuring proper JSON string formatting with backslashes for special characters.

Syntax:

array.map(callback(currentValue, index, array), thisArg) 
str.replace(regexp|substr, newSubstr|function)

Example: The below example uses Array.prototype.map() and String.prototype.replace() to add backslash in JSON string JavaScript.

JavaScript
let jStr = `{
    "name": "Geek", 
    "age": 22, 
    "city": "Delhi"
}`;
let res = Array.from(jStr).map(char => {
    if (char === '\\' || char === '"') {
        return '\\' + char;
    } else {
        return char;
    }
}).join('');

console.log(res);

Output
{
    \"name\": \"Geek\", 
    \"age\": 22, 
    \"city\": \"Delhi\"
}


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads