Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a better way to "Pretty Print" the json string than I'm using

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?

like image 810
Dmitry Avatar asked Apr 30 '18 22:04

Dmitry


People also ask

How do I pretty print a JSON string?

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.

How do I print a pretty JSON file?

Use json. dumps() method to prettyprint JSON properly by specifying indent and separators. The json. dumps() method returns prettyprinted JSON data in string format.

Which pipe is used for pretty printing the JSON value?

Angular json pipe is also useful for debugging purpose because it displays all the properties of the object in pretty print json format.


3 Answers

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.

Json received as Data from server

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
}

Pretty string for existing string

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)
like image 103
lukszar Avatar answered Nov 07 '22 11:11

lukszar


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")
}
like image 21
Elijah Avatar answered Nov 07 '22 11:11

Elijah


Use the output formatting option on the encoder directly:

let encoder = JSONEncoder()
encoder.outputFormatting = .prettyPrinted
like image 37
mnl Avatar answered Nov 07 '22 11:11

mnl