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.
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()
Contact Us