I have a string that needs to be parsed as JSON.
The problem is, it may sometimes contain double quotes, causing errors in parsing.
For example:
{
"id_clients":"58844",
"id_clients_name" : ""100" test"qw"
}
I need a regex to replace any double quotes between the opening and closing "
with a \"
.
Thanks.
I have a string that needs to be parsed as JSON.
The problem is, it may sometimes contain double quotes, causing errors in parsing.
For example:
{
"id_clients":"58844",
"id_clients_name" : ""100" test"qw"
}
I need a regex to replace any double quotes between the opening and closing "
with a \"
.
Thanks.
Share Improve this question edited May 15, 2013 at 14:47 Yurii Dolhikh asked May 15, 2013 at 14:37 Yurii DolhikhYurii Dolhikh 691 gold badge1 silver badge7 bronze badges 6- 2 You need to fix the problem at whatever is generating the JSON. – Explosion Pills Commented May 15, 2013 at 14:40
-
How do you know where is opening and closing
"
– anubhava Commented May 15, 2013 at 14:44 - First and last before/after the ':'. – Yurii Dolhikh Commented May 15, 2013 at 14:46
- I concur with @ExplosionPills, you need to use code that already knows how to build JSON if you can...those quotes should be escaped BEFORE you get the JSON string...otherwise, you're going to need some plex look-ahead/look-behind expressions that will likely get nasty. I'm better than most people with regexes (not an expert by any means) and I wouldn't want to figure this out. – Kevin Nelson Commented May 15, 2013 at 14:52
- e.g. what if your JSON does: "id_clients":""588","44"", how does it know to ignore the ", after 588 because it looks like JSON. – Kevin Nelson Commented May 15, 2013 at 14:54
2 Answers
Reset to default 5I tried it just for fun, even though it is certainly better to fix the generator. This might work in your case, or at least inspire you:
You can try it here
$( function()
{
var myString = "{ \"na\"\"me\": \"va\"lue\", \"tes\"\"t\":\"ok\" }";
var myRegexp = /\s*\"([\w\"]+)\"\s*[,}:]/g;
var match;
var matches = [];
// Save all the matches
while((match = myRegexp.exec(myString)) !== null)
{
matches.push(match[1]);
console.log(match[1]);
}
// Process them
var newString = myString;
for (var i=0; i<matches.length; i++)
{
var newVal = matches[i].replace(/\"/g, '\\\"');
newString = newString.replace(matches[i], newVal);
}
alert(myString + "\n" + newString);
}
);
You can try, although this will work only for the opening tags :
.replace(/\"\"/g, '\\""');