2

I pull json data from a server. It contains a dictionary with text that I insert into a html template.

How do I properly escape this string?

NSString* json = /* can be anything, but also garbage */
NSString* json_escaped = [json someEscapeMethod]; ///////  HOW TO ESCAPE THIS ?
NSString* script = [NSString stringWithFormat:@"process('%@')", json_escaped];
NSString* result = [self.webView stringByEvaluatingJavaScriptFromString:script];

I currently do like this, but I'm not sure wether the escaping is sufficiently

NSString* json_escaped = [json stringByReplacingOccurrencesOfString:@"'" withString:@"\\'"];
neoneye
  • 50,398
  • 25
  • 166
  • 151

2 Answers2

6

I now encode it this way, but the overhead is huge.

NSString* json = /* can be anything, but also garbage */
NSString* json_escaped = [json stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString* script = [NSString stringWithFormat:@"process('%@')", json_escaped];
NSString* result = [self.webView stringByEvaluatingJavaScriptFromString:script];

And decode it in javascript like this

function process(json_escaped) {
  var json = decodeURIComponent(json_escaped);
  alert('json: ' + json.toString());
}

I'm still looking for a better solution with less overhead.

Update

I have recently learned that there exists several frameworks for bridging objective-c with javascript.

Community
  • 1
  • 1
neoneye
  • 50,398
  • 25
  • 166
  • 151
  • 1
    This is almost right. if your original string contains single apostrophe this code will not work well. All you have to do in order to fix it is change process('%@') to process("%@"). single apostrophe (') is not getting encoded by stringByAddingPercentEscapesUsingEncoding where double apostrophe (") is. – Amir Naor Apr 14 '13 at 23:27
0

The "Escaping Characters in a String" section of NSRegularExpression may work.

torus
  • 1,039
  • 2
  • 11
  • 26