Skip to content

Instantly share code, notes, and snippets.

@cprovatas
Created May 23, 2018 15:52
Show Gist options
  • Save cprovatas/5c9f51813bc784ef1d7fcbfb89de74fe to your computer and use it in GitHub Desktop.
Save cprovatas/5c9f51813bc784ef1d7fcbfb89de74fe to your computer and use it in GitHub Desktop.
Pretty print JSON string from Data in Swift 4.1 (especially useful printing to Xcode console)
import Foundation
extension Data {
var prettyPrintedJSONString: NSString? { /// NSString gives us a nice sanitized debugDescription
guard let object = try? JSONSerialization.jsonObject(with: self, options: []),
let data = try? JSONSerialization.data(withJSONObject: object, options: [.prettyPrinted]),
let prettyPrintedString = NSString(data: data, encoding: String.Encoding.utf8.rawValue) else { return nil }
return prettyPrintedString
}
}
let str = "{\"foo\": \"bar\"}".data(using: .utf8)!.prettyPrintedJSONString!
debugPrint(str)
/* prints:
{
"foo" : "bar"
}
*/
@DevNebulae
Copy link

Using String instead of NSString won't do any harm (documentation).

@cprovatas
Copy link
Author

Using String instead of NSString won't do any harm (documentation).

@DevNebulae NSString intentional, note comment: /// NSString gives us a nice sanitized debugDescription

@Booharin
Copy link

Booharin commented Apr 1, 2022

Great!

@sinbadbd
Copy link

Yes! using NSString its seems to be awesome 👏

@AbduqaxxorSaidjonov
Copy link

Thank you

@littledogboy
Copy link

ty!!

@jimallan07
Copy link

Thank you

@algonrey
Copy link

Swifty version

extension Encodable {
    var prettyPrintedJSONString: String? {
        let encoder = JSONEncoder()
        encoder.outputFormatting = .prettyPrinted
        guard let data = try? encoder.encode(self) else { return nil }
        return String(data: data, encoding: .utf8) ?? nil
    }
}

Best option!! 😍

@Skovie
Copy link

Skovie commented Feb 17, 2024

thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment