Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prettyPrint json response from API call in debugger?

Trying to figure out how to prettyPrint the json value of my response from an API, while debugging:

let session = URLSession(configuration: .default)
let task = session.dataTask(with: urlRequest) { data, response, error in
    completion(data, response, error)
}

In the debugger, if I do po data, this is what I get something like this:

enter image description here

How can I print out the actual json structure that is in the data object? Was hoping to see something like this:

{ "firstName" : "John", "lastName" : "Doe", ... }

po debugPrint(data) doesn't output anything in this case.

like image 248
Prabhu Avatar asked Feb 19 '18 22:02

Prabhu


People also ask

How extract JSON data from API?

To receive JSON from a REST API endpoint, you must send an HTTP GET request to the REST API server and provide an Accept: application/json request header. The Accept header tells the REST API server that the API client expects JSON.


2 Answers

e print(String(data: JSONSerialization.data(withJSONObject: JSONSerialization.jsonObject(with: data, options: []), options: .prettyPrinted), encoding: .utf8)!)
like image 143
Ilias Karim Avatar answered Oct 18 '22 18:10

Ilias Karim


Try the JSONSerialization, something like this:

let url = URL(string: "http://date.jsontest.com")
var request : URLRequest = URLRequest(url: url!)
request.httpMethod = "GET"

let dataTask = URLSession.shared.dataTask(with: request) {
    data,response,error in
    do {
        if let jsonResult = try JSONSerialization.jsonObject(with: data!, options: []) as? NSDictionary {
            print(jsonResult)
        }
    } catch let error {
        print(error.localizedDescription)
    }
}
dataTask.resume()

Where jsonResult will print out this:

{
    date = "02-19-2018";
    "milliseconds_since_epoch" = 1519078643223;
    time = "10:17:23 PM";
}
like image 38
Rashwan L Avatar answered Oct 18 '22 20:10

Rashwan L