I have json data comes server side.
In case I use the next code I get not pretty printed one line string:
print(String(bytes: jsonData, encoding: String.Encoding.utf8))
To make it pretty printed I use the next code:
if let json = try? JSONSerialization.jsonObject(with: jsonData, options: .mutableContainers) {
if let prettyPrintedData = try? JSONSerialization.data(withJSONObject: json, options: .prettyPrinted) {
print(String(bytes: prettyPrintedData, encoding: String.Encoding.utf8) ?? "NIL")
}
}
But seems that it isn't the best way.
So does anybody know how to pretty print incoming jsonData to print it?
Use JSON. stringify(obj) method to convert JavaScript objects into strings and display it. Use JSON. stringify(obj, replacer, space) method to convert JavaScript objects into strings in pretty format.
Use json. dumps() method to prettyprint JSON properly by specifying indent and separators. The json. dumps() method returns prettyprinted JSON data in string format.
Angular json pipe is also useful for debugging purpose because it displays all the properties of the object in pretty print json format.
Basically in Swift exists 2 types for strings: String and NSString
The second one is older (used even in Objective-C) and nowadays more often is used newer String type. However, NSString allows you to pretty print existing strings, which means that f.ex. backslashes will be deleted automatically.
For this case I use such helper:
extension Data {
var prettyString: NSString? {
return NSString(data: self, encoding: String.Encoding.utf8.rawValue) ?? nil
}
}
It's very important to use NSString over String type.
Alternatively you can operate on String, but in the end cast it to AnyObject, like below:
String(data: stringData, encoding: .utf8)! as AnyObject
The result in console looks like this (example of server response):
{
"message" : "User could not log in",
"errorCode" : "USER_COULD_NOT_LOG_IN",
"parameters" : null
}
To prettify any string you can use second method from above, so cast String to AnyObject. It will also make string looking better. F.ex.:
let myStr: String = ...
print(myStr as AnyObject)
A slightly prettier version of what you have:
if let json = try? JSONSerialization.jsonObject(with: data, options: .mutableContainers),
let jsonData = try? JSONSerialization.data(withJSONObject: json, options: .prettyPrinted) {
print(String(decoding: jsonData, as: UTF8.self))
} else {
print("json data malformed")
}
Use the output formatting option on the encoder directly:
let encoder = JSONEncoder()
encoder.outputFormatting = .prettyPrinted
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With