Reputation: 4493
I'm trying to replace single quotes in my json string values with \' however it is not working only when I try to use the replacer function.
var myObj = {
test: "'p'"
}
var replacer = function (key, value) {
if (typeof value === 'string')
return value.replace(/'/g, "\\'");
else return value;
};
var JSONstring = JSON.stringify(myObj, replacer, ' ');
alert(JSONstring);
https://jsfiddle.net/4fsqozek/1/
However if I do just a simple replace after the string is created like this without using the replacer function
var JSONstring = JSON.stringify(myObj).replace(/'/g, "\\'");
The regex I used works fine.
EDIT - clarification - using replacer function the output value contains double backslash like this \\'p\\' , which is not what I'm expecting
Can anyone explain this?
Upvotes: 0
Views: 3887
Reputation: 26
The value is passed to the replacer before it is stringified. The replacer's escapes are stripped out when the value gets stringified.
This is why calling replace() after the json has been stringified works.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
Upvotes: 0
Reputation: 15847
JSON.stringify
encodes backslashes
see How do I retain backslashes in strings when using JSON.stringify?
As you attempt to insert a backslash in a string that will be JSON encoded the single \
will become \\
However as you will decode the JSON double backslashes \\
then will be decoded into single \
(and I think you'll end up with the desired result).
If you keep your exact code and then at the end you replace the alert(...)
with
alert( JSON.parse( JSONstring ).test );
you get
\'p\'
Upvotes: 2