How to use JSON.parse() and JSON.stringify() In Javascript

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\"}

How to Add Backslash in JSON String JavaScript ?

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.

Table of Content

  • Using JSON.parse() and JSON.stringify()
  • Using for Loop
  • Using Array.prototype.map() and String.prototype.replace()

Similar Reads

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....

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....

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....

Contact Us