JSON Serialization in Swift: Writing options

Seamless Data Handling

Balraj Verma
3 min readJun 29, 2023
Photo by Markus Spiske on Unsplash

Do those actually help?

I considered including this information in my earlier JSON-related Swift blog post about handling snake cases. However, it’s best to keep it separate because it’s sort of a different property and useful for sometimes logging or sending your JSON over network requests. This will again be a microblog, so let’s start

You may have seen some code similar to the one below while using Swift to parse JSON. The parameter ‘options’ (Writing options) will be the topic of discussion in this section.

_ = try JSONSerialization.jsonObject(with: jsonData, options: []) as? [String: Any] {

Swift offers three different ways to structure and serialize your output so that it may be sent via a network request.

i)prettyPrinted The JSON string that results from converting the Swift object to JSON data will be structured with indentation and line breaks for easier reading if the `.prettyPrinted` option is used.

Let’s see an example

let jsonObject: [String: Any] = [
"name": "Ron",
"age": 30,
"employerDetails": [
"employeeID": "01234",
"jobLocation": "Remote"
"expertise": ["c", "c++", "html", "java"]
let jsonData = try JSONSerialization.data(withJSONObject: jsonObject, options: [])

// Convert JSON data to a string for printing or further use
if let jsonString = String(data: jsonData, encoding: .utf8) {

// : Response if no option is provided

// :Respnose if prettyPrinted is used,
"age" : 30,
"employerDetails" : {
"jobLocation" : "Remote",
"employeeID" : "01234"
"name" : "Ron",
"expertise" : [

ii)sortedKeys The keys in the resulting .sortedkeys JSON strings are arranged alphabetically. See the response below

/* response when sortedKeys is being used

iii)fragmentsAllowed This is crucial because, in cases where there aren’t any top-level objects in the JSON object if the right options weren’t provided when serializing the JSON object, it can cause your app to crash. Let’s use a specific example to help you comprehend it.

//unusual json string that is just an object and not an array or dictionary on top level. 
let jsonString = """
_ = try JSONSerialization.jsonObject(with: jsonData, options: []) as? String

The application will crash and display the following error if you attempt to serialize the JSON string using the aforementioned API. JSON has an invalid top-level type. The outcome is shown below if you use .fragmentAllowed with the same JSON as before.

/* Crashing Error
+[NSJSONSerialization dataWithJSONObject:options:error:]: Invalid top-level type in JSON write'
//Now use the API
_ = try JSONSerialization.data(withJSONObject: jsonString, options: .fragmentsAllowed)

//This is the response from using fragmentsAllowed

That’s it.

I hope you enjoy this brief blog post and that I was able to share some useful information that we occasionally overlook while working with APIs like this. Vote it up if you enjoy this site. I’ll see you in the next one 👋 !!!