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 }
It is very useful to prevent the error: Domain=NSCocoaErrorDomain Code=3840 "Invalid escape sequence around character 123."
source share