Forum Cross Platform with Xamarin
We are excited to announce that the Xamarin Forums are moving to the new Microsoft Q&A experience. Q&A is the home for technical questions and answers at across all products at Microsoft now including Xamarin!

We encourage you to head over to Microsoft Q&A for .NET for posting new questions and get involved today.

How to escape a JSON object to feed into a JavaScript function?

This is not exactly a Xamarin-specific problem so apologies if this is not the right place for it!

I'm building an Android and iPhone application that shows a WebView (UIWebView on iOS). The WebView has an HTML page loaded in it which contains a simple JavaScript function defined as follows:

function parseJson(input)
  alert("start of parseJson(...) JavaScript method");
  var parsedJson = JSON.parse(input);
  alert("end of parseJson(...) JavaScript method");

What I want to do is to call my parseJson(input) JavaScript function from the Android/iOS client passing in a string as the input parameter. This is done as follows for Xamarin.Android:

string json = "{}"
myWebView.LoadUrl ("javascript:parseJson(\" + json + \")"));

And as follows for Xamarin.iOS:

string json = "{}"
myWebView.EvaluateJavascript ("parseJson(\" + json + \")");

Up to here, this works fine. No problem. The JavaScript function is called and executes. Also, I know I have to double-escape the quotation-mark character in my string, as follows:

string json = "{\\\"key\\\":\\\"value\\\"}";

This also works fine. The JavaScript function is called and executes. Double escaping "\r" and "\n" (to "\\\r" and "\\\n") also works. However, if the JSON string contains a "\\", "\b", "\t" or "\f", then the JSON.parse(...) call in my JavaScript function falls over (even if the character is double-escaped).

Anyone here ever encountered this or a similar problem and know how I can reliably escape my JSON string from within the client before I feed it into my JavaScript function?


Sign In or Register to comment.