Configuring JSONEncoder output in Swift
When using JSONEncoder with a Codable object in Swift, you may have slashes in one of the data values, e.g. a URL. This article shows how you can modify the default format for the slashes.
The following code shows a way to use JSONEncoder to produce a JSON string for a ConferenceSpeaker
struct.
struct ConferenceSpeaker: Codable {
var name: String
var website: String?
}
let speaker = ConferenceSpeaker(name: "Neil Taylor", website: "https://digidol.ghost.io/")
let encoder = JSONEncoder()
encoder.outputFormatting = .prettyPrinted
let data = try encoder.encode(speaker)
print(String(data: data, encoding: .utf8)!)
The default output with the .prettyPrinted
format option is shown below.
{
"name" : "Neil Taylor",
"website" : "https:\/\/digidol.ghost.io\/"
}
The JSONEncoder has added the \
escape character before each /
character. It is valid JSON, but it might be that you don't want that character in your output.
To change this, you can use the .withoutEscapingSlashes
format option.
If you use it instead of .prettyPrinted
, then you get the following output.
{"name":"Neil Taylor","website":"https://digidol.ghost.io/"}
If you want to have pretty printing and not escape the slashes, you can provide an array of options. Changing the code to the following will provide both format options.
struct ConferenceSpeaker: Codable {
var name: String
var website: String?
}
let speaker = ConferenceSpeaker(name: "Neil Taylor", website: "https://digidol.ghost.io/")
let encoder = JSONEncoder()
encoder.outputFormatting = [.prettyPrinted, .withoutEscapingSlashes]
let data = try encoder.encode(speaker)
print(String(data: data, encoding: .utf8)!)
The output the changes to the following.
{
"name" : "Neil Taylor",
"website" : "https://digidol.ghost.io/"
}