Swift String escaping when serializing to JSON using Codable Swift String escaping when serializing to JSON using Codable ios ios

Swift String escaping when serializing to JSON using Codable


For iOS 13+ / macOS 10.15+

You can use .withoutEscapingSlashes option to json decoder to avoid escaping slashes

let user = User(username: "John", profileURL: "http://google.com")let jsonEncoder = JSONEncoder()jsonEncoder.outputFormatting = .withoutEscapingSlasheslet json = try? jsonEncoder.encode(user)if let data = json, let str = String(data: data, encoding: .utf8) {    print(str)}

Console O/P

{"profileURL":"http://google.com","username":"John"}


NOTE: As mention by Martin R in comments \/ is a valid JSON escape sequence.


I ended up using replacingOccurrences(of:with:), which may not be the best solution, but it resolves the issue:

import Foundationstruct User: Codable {    let username: String    let profileURL: String}let user = User(username: "John", profileURL: "http://google.com")let json = try? JSONEncoder().encode(user)if let data = json, let str = String(data: data, encoding: .utf8)?.replacingOccurrences(of: "\\/", with: "/") {    print(str)    dump(str)}


I got it. The thing was that it didn't contain any \ character. It is just the property of swift that it will always return such a string on a console. The workaround is to j-son parse it.

Still, you can be used below solution of replacing '\/' with "/" string

 let newString = str.replacingOccurrences(of: "\\/", with: "/")  print(newString)