Reputation: 81
I want to remove some special character from json
without parsing
the json
into object
.
Parsing would result into error that is why i wanted to do without json.parse()
.
below is my json:
{
"id":324,
"name":"first",
"body":{
"sbody": "<p>\\\The New Stroy\\\</p>"
}
}
desired output:
{
"id":324,
"name":"first",
"body":{
"sbody": "<p> The New Stroy </p>"
}
}
Upvotes: 0
Views: 18794
Reputation: 1565
var obj = {
"id":324,
"name":"first",
"body":{
"sbody": "<p>\\\The New Stroy\\\</p>"
}
}
// Convert object to string
var str = JSON.stringify(obj);
// Remove \ from the string
var convertedStr= str.replace(/\\/g,'');
// Convert updated string back to object
var newObj = JSON.parse(convertedStr);
Upvotes: 1
Reputation: 14891
You need to run .replace
on your string:
var string = '{"id":324,"name":"first","body":{"sbody":"<p>\\\The New Stroy\\\</p>"}}';
string = string.replace(/\\/g,'');
console.log(string);
//{"id":324,"name":"first","body":{"sbody":"<p>The New Stroy</p>"}}
The reason the pattern is /\\/
is because \
is used to escape characters. With a single \
we end up escaping the /
. What we need to do here is escape the escape character to turn it into a literal string character: \\
.
The g
after the pattern means to search for the pattern "globally" in the string, so we replace all instances of it.
Upvotes: 1
Reputation: 34147
Looks like your input is a string and the error you are getting is when using JSON.parse
.
Try this
var response = '{"sbody": "<p>\\\The New Stroy\\\</p>"}';
response = response.replace(/\\/g, "");
var obj = JSON.parse(response);
console.log(obj);
Upvotes: 1