Swift Data to JSON String: Formatting and Pretty Printing

JSON data is often not human-readable because web servers strip all white space to save bandwidth.

Converting JSON data into a formatted string helps build decodable Swift types and is useful for debugging, saving data to a JSON File, and writing unit tests for an app’s JSON output.



FREE GUIDE: Parsing JSON in Swift - The Ultimate Cheat Sheet

Learn the fundamentals of JSON parsing in Swift, advanced decoding techniques, and tasks for app development

DOWNLOAD THE FREE GUIDE

If all you need to do is format the JSON data you got from a REST API, you can copy and paste it inside an online JSON formatter.

However, you often need to pretty-print the JSON data inside your app, for example when fetching it from an API URL. In that case, you must first convert it into a Swift value and revert it into formatted JSON data.

The simplest way is to use the JSONSerialization class, which does not require creating any extra Codable Swift type. The JSONSerialization class converts JSON data into basic Foundation types and collections.

import Foundation

let json = #"{"name":"John Doe","age":30,"employers":["Apple","Facebook","Google"]}"#
let data = json.data(using: .utf8)!
let object = try JSONSerialization.jsonObject(with: data)
let prettyPrintedData = try JSONSerialization.data(
	withJSONObject: object,
	options: [.prettyPrinted, .sortedKeys]
)
let prettyPrintedString = String(data: prettyPrintedData, encoding: .utf8)!
print(prettyPrintedString)

If you have a Codable Swift type instead, you can decode the JSON data using a JSONDecoder instance and re-encode it using a JSONEncoder instance.

struct Person: Codable {
	let name: String
	let age: Int
	let employers: [String]
}

let json = #"{"name":"John Doe","age":30,"employers":["Apple","Facebook","Google"]}"#
let data = json.data(using: .utf8)!
let person = try JSONDecoder().decode(Person.self, from: data)
let encoder = JSONEncoder()
encoder.outputFormatting = [.prettyPrinted, .sortedKeys]
let prettyPrintedData = try encoder.encode(person)
let prettyPrintedString = String(data: prettyPrintedData, encoding: .utf8)!
print(prettyPrintedString)

In both cases, do not forget the .prettyPrinted option.

Adding the .sortedKeys option will alphabetically sort the members inside all JSON objects. This is useful when creating unit tests to verify the encoding output.

{
  "age" : 30,
  "employers" : [
    "Apple",
    "Facebook",
    "Google"
  ],
  "name" : "John Doe"
}

If you want a quick reference these pretty printing code snippets, together with other JSON parsing techniques, download my free cheat sheet below.

FREE GUIDE: Parsing JSON in Swift - The Ultimate Cheat Sheet

Learn the fundamentals of JSON parsing in Swift, advanced decoding techniques, and tasks for app development

DOWNLOAD THE FREE GUIDE

Leave a Comment