Reputation: 11707
How do I escape a double quote ("
) inside double quotes using a regular expression for the JSON string below?
[{
"LDAP_ID":"a",
"LAC_NO":"1153274",
"ACTION":"VBE",
"DATE_OF_ACTION":"06-01-2006 AM 12:00:00",
"RESPONSE":"DPP",
"DEF_OBSERV":"M",
"REMARK":"visited b" s emp & rcd 1 emi",
"OPR_ID":"FCTV1",
"ACTION_TO_BE":"",
"ACTION_TO_BE_DT":"",
"AMOUNT_TOBECHG":"",
"DELEGATED_TO":"",
"BRANCH_CODE":"100",
"DISP_DATE_OF_ACTION":"06-JAN-06",
"DISP_ACTION_TO_BE_DT":"",
"SRNO":"142871",
"DELETED_FLAG":"",
"TIMESTAMP":"10-08-2012 AM 11:38:30",
"STAMPDATETIME":"2012-08-10 11:38:30"
}]
Key line needing escaped:
"REMARK":"visited b" s emp & rcd 1 emi",
Upvotes: 0
Views: 2107
Reputation: 695
The only way to fix that invalid JSON within JS with regular expressions is to receive it as string, do the replacement and then re-evaluate it as JSON. This last step can be unsafe. Here is a question with a similar problem: Convert object string to JSON
So I would suggest to fix the JSON before receiving it. Anyway, if you can't, here's a solution with regular expressions.
The regular expression only operates between the delimiters of a value :" and ", to make sure to escape only double quotes within a value (edited).
:\s*"[^"]*"[^"]*"\s*(,|\s*\})
Here's the full code with the replacement (regex edited):
var str = '[{ "LDAP_ID":"a", "LAC_NO":"1153274", "ACTION":"VBE", "DATE_OF_ACTION":"06-01-2006 AM 12:00:00", "RESPONSE":"DPP", "DEF_OBSERV":"M", "REMARK":"visited b" s emp & rcd 1 emi", "OPR_ID":"FCTV1", "ACTION_TO_BE":"", "ACTION_TO_BE_DT":"", "AMOUNT_TOBECHG":"", "DELEGATED_TO":"", "BRANCH_CODE":"100", "DISP_DATE_OF_ACTION":"06-JAN-06", "DISP_ACTION_TO_BE_DT":"", "SRNO":"142871", "DELETED_FLAG":"", "TIMESTAMP":"10-08-2012 AM 11:38:30", "STAMPDATETIME":"2012-08-10 11:38:30" }]'
var j = str.replace(/(:\s*"[^"]*)"([^"]*"\s*(,|\s*\}))/g, '$1\\"$2');
var json = JSON.stringify(eval("(" + j + ")"));
Upvotes: 0
Reputation: 20885
This problem can't be solved with a regular expression. You can even came up with one that works in 99% of the cases, but nothing more.
Invalid JSON is invalid, and must be fixed by a human on the server side. Regex are not intended to solve this kind of problems. You'd better fix it on the server side.
Upvotes: 2