4

I have a NSString that may contain quotes,\, /, \r, \n, and I want to convert it to a JSON encoded string so strings like this

"text1\text2"

becomes

\"text1\\text2\"

Is there a existing function to let me do this?

Also, I am using SBJson in my project but I cannot find whether SBJson can do this or not.

NSJSONSerialization is not on the table since my application still needs to support OSX 10.6

lakeskysea
  • 591
  • 3
  • 8
  • 15

4 Answers4

13

Does this answer your question?

-(NSString *)JSONString:(NSString *)aString {
    NSMutableString *s = [NSMutableString stringWithString:aString];
    [s replaceOccurrencesOfString:@"\\" withString:@"\\\\" options:NSCaseInsensitiveSearch range:NSMakeRange(0, [s length])];
    [s replaceOccurrencesOfString:@"\"" withString:@"\\\"" options:NSCaseInsensitiveSearch range:NSMakeRange(0, [s length])];
    [s replaceOccurrencesOfString:@"/" withString:@"\\/" options:NSCaseInsensitiveSearch range:NSMakeRange(0, [s length])];
    [s replaceOccurrencesOfString:@"\n" withString:@"\\n" options:NSCaseInsensitiveSearch range:NSMakeRange(0, [s length])];
    [s replaceOccurrencesOfString:@"\b" withString:@"\\b" options:NSCaseInsensitiveSearch range:NSMakeRange(0, [s length])];
    [s replaceOccurrencesOfString:@"\f" withString:@"\\f" options:NSCaseInsensitiveSearch range:NSMakeRange(0, [s length])];
    [s replaceOccurrencesOfString:@"\r" withString:@"\\r" options:NSCaseInsensitiveSearch range:NSMakeRange(0, [s length])];
    [s replaceOccurrencesOfString:@"\t" withString:@"\\t" options:NSCaseInsensitiveSearch range:NSMakeRange(0, [s length])];
    return [NSString stringWithString:s];
}

Source: converting NSString to JSON string

Doron Yakovlev Golani
  • 5,188
  • 9
  • 36
  • 60
Jean
  • 7,623
  • 6
  • 43
  • 58
  • How about a few lines of code for escaping non-printable characters? `\U1234`, etc. –  Apr 05 '13 at 21:12
  • A quick follow-up: does a single "\" need to be processed too? It is in the diagram but not in the code. – lakeskysea Apr 10 '13 at 08:17
  • Well, the displayed code only deals with `"`, `/`, `b`, `f`, `n`, `r`, `t`, `u`. ` \ ` and `u[4 hex digits]` are left out. I have always used the above code without any trouble. I suppose `\u1234` and ` \ ` are handled correctly. Please, let me know if you encounter any trouble with the above code. – Jean Apr 10 '13 at 11:12
  • 3
    @lakeskysea Yes, the existing snippet is not comprehensive. You'll need to add something like `[s replaceOccurrencesOfString:@"\\" withString:@"\\\\" options:NSCaseInsensitiveSearch range:NSMakeRange(0, [s length])];` to correctly handle a backslash character. – Daniel S. Jun 17 '13 at 03:00
  • @DanielS.Thanks for your solution it solved my problem. – ViruMax Jul 27 '17 at 09:14
4

let's do it in more-native-JSON-way ;)

If u like my answer, please star me at https://github.com/wanjochan

//trick: id(@[s]) => string => trim [] => target
//NSString *s
s=[[NSString alloc] initWithData:
  [NSJSONSerialization dataWithJSONObject:@[s] options:0 error:nil]
  encoding:NSUTF8StringEncoding];
s=[[s substringToIndex:([s length]-1)] substringFromIndex:1];
mgttt
  • 351
  • 3
  • 4
0

Swift 2:

/// Escape reserved characters to produce a valid JSON String
/// For example double quotes `"` are replaced by `\"`
/// - parameters:
///   - String: an unescaped string
/// - returns: valid escaped JSON string
func JSONString(str: String?) -> String? {
    var result : String? = nil
    if let str = str {
        result = str
            .stringByReplacingOccurrencesOfString("\"", withString: "\\\"", options: .CaseInsensitiveSearch)
            .stringByReplacingOccurrencesOfString("/", withString: "\\/", options: .CaseInsensitiveSearch)
            .stringByReplacingOccurrencesOfString("\n", withString: "\\n", options: .CaseInsensitiveSearch)
            .stringByReplacingOccurrencesOfString("\u{8}", withString: "\\b", options: .CaseInsensitiveSearch)
            .stringByReplacingOccurrencesOfString("\u{12}", withString: "\\f", options: .CaseInsensitiveSearch)
            .stringByReplacingOccurrencesOfString("\r", withString: "\\r", options: .CaseInsensitiveSearch)
            .stringByReplacingOccurrencesOfString("\t", withString: "\\t", options: .CaseInsensitiveSearch)
    }
    return result
}

Swift 3:

func JSONString(str: String) -> String {
    var result = str
    result = result.replacingOccurrences(of: "\"", with: "\\\"")
        .replacingOccurrences(of: "/", with: "\\/")
        .replacingOccurrences(of: "\n", with: "\\n")
        .replacingOccurrences(of: "\u{8}", with: "\\b")
        .replacingOccurrences(of: "\u{12}", with: "\\f")
        .replacingOccurrences(of: "\r", with: "\\r")
        .replacingOccurrences(of: "\t", with: "\\t")

    return result
}

Very useful to prevent error: Domain=NSCocoaErrorDomain Code=3840 "Invalid escape sequence around character 123."

tomtclai
  • 333
  • 6
  • 18
rjobidon
  • 3,055
  • 3
  • 30
  • 36
0

Swift 4 Solution

extension String {
    var stringEncodedJSON: String {
        var copy = self
        let encodingDict: [String: String] = ["\"": "\\\"", "/": "\\/", "\n": "\\n", "\u{8}": "\\b","\u{12}": "\\f", "\r": "\\r", "\t": "\\t"]
        encodingDict.forEach({ copy = copy.replacingOccurrences(of: $0, with: $1) })
        return copy
    }
}
Charlton Provatas
  • 2,184
  • 25
  • 18