Convert certain characters to escaped unicode version

I have a NSString containing possible unwanted characters that I have to convert to the escaped unicode version. More specifically, I need to pass a JSON object (serialized as a string) to a UIWebView via it's script evaluation method, and some characters tend to raise a JS exception.

So I want to encode all characters mentioned to be unsafe by JSLint which are:

\u0000-\u001f
\u007f-\u009f
\u00ad
\u0600-\u0604
\u070f
\u17b4
\u17b5
\u200c-\u200f
\u2028-\u202f
\u2060-\u206f
\ufeff
\ufff0-\uffff

and replace them with their escaped equivalents.

What's the best way to do this?

UPDATE: Somehow \u2028 (line separator char) snuck in the JSON

Answers


Well, it's not exactly the solution I had in mind, but trimming is also a suitable option

  // Remove unsafe JSON characters
  //
  // http://www.jslint.com/lint.html#unsafe
  //
  if (jsonStr.length > 0) {
    NSMutableCharacterSet *unsafeSet = [NSMutableCharacterSet new];
    void (^addUnsafe)(NSInteger, NSInteger) = ^(NSInteger from, NSInteger to) {
      if (to > from) {
        [unsafeSet addCharactersInRange:NSMakeRange(from, (to - from) + 1)];
      } else {
        [unsafeSet addCharactersInRange:NSMakeRange(from, 1)];
      }          
    };

    addUnsafe(0x0000, 0x001f);
    addUnsafe(0x007f, 0x009f);
    addUnsafe(0x00ad, 0);
    addUnsafe(0x0600, 0x0604);
    addUnsafe(0x070f, 0);
    addUnsafe(0x17b4, 0);
    addUnsafe(0x17b5, 0);
    addUnsafe(0x200c, 0x200f);
    addUnsafe(0x2028, 0x202f);
    addUnsafe(0x2060, 0x206f);
    addUnsafe(0xfeff, 0);
    addUnsafe(0xfff0, 0xffff);

    jsonStr = [[jsonStr componentsSeparatedByCharactersInSet:unsafeSet] componentsJoinedByString:@""];
  }

Need Your Help

Date format issue in ios7

ios iphone nsdateformatter

I am facing a a strange issue in date. i am getting varied results on the time format.

Title Heading for Tree R Package

r plot tree

I want to add a main title heading to the plot output of a tree model.