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>"
}
}
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>"
}
}
Share
Improve this question
edited Oct 19, 2018 at 10:33
Federico klez Culloca
27.2k17 gold badges60 silver badges102 bronze badges
asked Oct 19, 2018 at 10:27
EaBengaluruEaBengaluru
892 gold badges30 silver badges73 bronze badges
4
-
1
Given the syntax, what you appear to have is an object, not JSON. Therefore any use of
JSON.parse
is irrelevant. – Rory McCrossan Commented Oct 19, 2018 at 10:28 - What are those special character? Just slashes? Repeated slashes? Invalid escape sequences? – Federico klez Culloca Commented Oct 19, 2018 at 10:28
- Why would you not want to parse it? To ensure you know you're looking at a string you'll end up with a parser. – Richard Commented Oct 19, 2018 at 10:28
- Is your input a response from ajax call? – kiranvj Commented Oct 19, 2018 at 10:34
3 Answers
Reset to default 1Looks 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);
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.
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);