Here's the full code:
//turn an NSObject into an NSString
+ (NSString *)jsonDumps:(id)obj {
NSError *error;
NSData *utf8stringified = [NSJSONSerialization dataWithJSONObject:obj options:0 error:&error];
if (utf8stringified == nil) {
[NSException raise:@"Failed to jsonify arguments" format:@"Failed to jsonify arguments %@: %@",
obj, error];
}
NSString *stringified = [[[NSString alloc] initWithData:utf8stringified encoding:NSUTF8StringEncoding]
autorelease];
return stringified;
}
//turn a JSON string into a JS literal
+(NSString *)jsonToJSLit:(NSString *)jsonString {
NSMutableString *s = [NSMutableString stringWithString:jsonString];
[s replaceOccurrencesOfString:@"\u2028" withString:@"\\u2028" options:NSCaseInsensitiveSearch range:NSMakeRange(0, [s length])];
[s replaceOccurrencesOfString:@"\u2029" withString:@"\\u2029" options:NSCaseInsensitiveSearch range:NSMakeRange(0, [s length])];
return [NSString stringWithString:s];
}
//turn an object into a JS string literal
+(NSString *)objToJSLiteral:(id)obj {
return [self jsonToJSLit:[self jsonDumps:obj]];
}
I thought there was more of a difference between JSON and JS literals, but apparently it's just those two unicode characters!