Print pretty JSON in Swift 5

When dealing with REST APIs and JSON data in iOS it can be very useful to be able to see the data in raw string format. With this small extension you can print JSON data as an optional string from a Data object:

extension Data {
    var prettyJSON: String? {
        guard let object = try? JSONSerialization.jsonObject(with: self, options: []),
              let data = try? JSONSerialization.data(withJSONObject: object, options: [.prettyPrinted])
        else { return nil }
        
        return String(data: data, encoding: .utf8)
    }
}

Now, consider the following struct:

struct Person: Codable {
    var name: String
    var age: Float
}

And then lets create an array of people and encode it into data:

let people = [
    Person(name: "Gunther", age: 24.5),
    Person(name: "Viktor", age: 33)
]

let data = try? JSONEncoder().encode(people)

Now we can use the extension and print the data in pretty json:

print(data?.prettyJSON ?? "")

/*
[
  {
    "name" : "Gunther",
    "age" : 24.5
  },
  {
    "name" : "Viktor",
    "age" : 33
  }
]
*/