Skip to content

Instantly share code, notes, and snippets.

@perseusrealdeal
Last active January 15, 2024 10:46
Show Gist options
  • Save perseusrealdeal/945c9050cb9f7a19e00853f064acacca to your computer and use it in GitHub Desktop.
Save perseusrealdeal/945c9050cb9f7a19e00853f064acacca to your computer and use it in GitHub Desktop.
Pretty printed Json Data object as a NSString.
//
// JsonDataPrettyPrintedGift.swift
// Gifts
//
// Just a gift, tested with Swift 4.2 compiler.
// https://gist.github.com/perseusrealdeal/945c9050cb9f7a19e00853f064acacca
//
/* Perseus Logger source code */
/* https://gist.github.com/perseusrealdeal/df456a9825fcface44eca738056eb6d5 */
import Foundation
extension Data {
/* Inspired by the following gist, many thanks. */
/* https://gist.github.com/cprovatas/5c9f51813bc784ef1d7fcbfb89de74fe */
public var prettyPrinted: NSString? {
let opts: JSONSerialization.WritingOptions = [.prettyPrinted]
let enc: UInt = String.Encoding.utf8.rawValue
do {
let object = try JSONSerialization.jsonObject(with: self, options: [])
let data = try JSONSerialization.data(withJSONObject: object, options: opts)
guard
let prettyPrinted = NSString(data: data, encoding: enc)
else {
// log.message("[\(type(of: self))].\(#function), NSString", .error)
return nil
}
return prettyPrinted
} catch {
// log.message("[\(type(of: self))].\(#function) \(error)", .error)
return nil
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment