Last Updated: February 25, 2016
·
824
· novalagung

iOS - Fixing non-quoted-key in JSON String

+ (NSString *)fixJSON:(NSString *)s {
    NSRegularExpression *regexp = [NSRegularExpression regularExpressionWithPattern:@"[{,]\\s*(\\w+)\\s*:"
                                                                            options:0
                                                                              error:NULL];
    NSMutableString *b = [NSMutableString stringWithCapacity:([s length] * 1.1)];
    __block NSUInteger offset = 0;
    [regexp enumerateMatchesInString:s
                             options:0
                               range:NSMakeRange(0, [s length])
                          usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) {
                              NSRange r = [result rangeAtIndex:1];
                              [b appendString:[s substringWithRange:NSMakeRange(offset, r.location - offset)]];
                              [b appendString:@"\""];
                              [b appendString:[s substringWithRange:r]];
                              [b appendString:@"\""];
                              offset = r.location + r.length;
                          }];
    [b appendString:[s substringWithRange:NSMakeRange(offset, [s length] - offset)]];
    return b;
}