0

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?

0

2 Answers 2

2

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\'
Sign up to request clarification or add additional context in comments.

2 Comments

I didn't realize what I was trying to do resulted in invalid json, because it was all wrapped inside the double quotes I thought what was inside didn't matter and was treated like a string
@erotavlas yes, I didn't mentioned but actually the JSON with "forced" single backslashes would have been non-compliant with JSON specs.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.