How to print formatted JSON in SwiftUI

To print a JSON object in a formatted JSON string in SwiftUI, you can use the JSONSerialization class from the Foundation framework to encode the JSON object into a Data object, and then use the String initializer to convert the Data object into a formatted JSON string. Here is an example of how to do this:

Create a file named Data + Extensions.swift

Add the following code to it:

import Foundation

extension Data {
    func prettyPrint() {
            do {
                let jsonObject = try JSONSerialization.jsonObject(with: self, options: [])
                let prettyPrintedData = try jsonObject, options: .prettyPrinted)
                // Put the guard to handle invalid json
                guard let jsonString = String(data: prettyPrintedData, encoding: .utf8) else {
                    print("Data is not in a valid json")
            } catch {
                print("Error: \(error.localizedDescription)")

You can then call the above function from your JSON object:


It will print the object in formatted manner.