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
  }
]
*/

12 comments on “Print pretty JSON in Swift 5”

  1. Pingback: larotid

  2. Pingback: zithromax without dr prescription

  3. Pingback: ciproxina

  4. Pingback: generic antibiotics online pharmacy

  5. Pingback: furosemide for dogs 20mg

  6. Pingback: viagra buy now

  7. Pingback: sildenafil cenforce 100

  8. Pingback: tabletki vidalista 20

  9. Pingback: sildenafil

  10. Pingback: cyclosporine nephrotoxicity symptoms

  11. Pingback: who makes orlistat

  12. Pingback: famotidine for infants

Comments are closed.