I've got a situation where some objects are being serialized into JSON using Json.NET, and then registered as a client script block. The object's JSON gets put into the javascript in a single quote literal kind of like this:
// javascript output, normal
reportParameters = '{ "Location" : "My house" }';
But sometimes it needs to put in values that contain apostrophes, like "Billy's House", so obviously I'm going to need to escape this or else the javascript breaks.
// javascript output scenario, bad
reportParameters = '{ "Location" : "Billy's House" }';
// what I need is this
reportParameters = '{ "Location" : "Billy\'s House" }';
I tried to do this:
// C# input
reportParameterText = reportParameterText.Replace("'", @"\'");`
However, this always changes it to "Billy\\'s House", and I cannot tell why. A lot of places where people have had similar problems say "It's just the debugger's way of representing one backslash," but in my case I still get 2 backslashes making its way into the javascript, so the backslash gets escaped instead of the apostrophe and everything breaks.
// javascript actual output, bad
reportParameters = '{ "Location" : "Billy\\'s House" }';
I've followed it through the debugger, and it has two backslashes before and after it gets serialized, so the serializer is not the problem. And as I said before it's definitely NOT just the debugger's representation of an escaped character, because these values are making it into the source code.
Other solutions I've tried, all C#:
reportParameterText = reportParameterText.Replace("'", "\'"); // No change
reportParameterText = reportParameterText.Replace("'", "\\'"); // Creates 2 backslashes
reportParameterText = reportParameterText.Replace("'", @"[%]");
reportParameterText = reportParameterText.Replace(@"[%]", @"\'"); // Creates 2 backslashes
The Question: Why am I always getting 2 backslashes, and how can I make sure I only put down one?
This is .Net 4.
SOLUTION
Thanks for all your help and information, everyone. I've solved my problem by combining several people's advice and essentially doing what @Ali123 suggested. As for the C# question of "Where is the second backslash coming from," it has to do with @Gusman's answer below.
My serialized string in C# is not safe as a string in Javascript, but it was still well-formed JSON. The JS black box of whatever accepts the string of a JSON object that was left lying around in the reportParameters
variable, but that doesn't mean that I have to get that stringified JSON in C#.
So instead of String.Replace in C#, I've prepared the generated JS code to look like this:
var tempThing = { "Location" : "Billy's House" };
reportParameters = JSON.stringify(tempThing);
StartDoingThings();
Looking at it again, I can cut a line out of that, but it still works.
TL;DR thanks, I know it was a slightly confusing problem.