Parsing JSON Array of Dictionaries
Solution 1
This is an example how you can read the data:
for data: Dictionary<String, Any> in idk{
if let address = data["address"] as? Dictionary<String, Any>{
//here the data in address: { .. } is available
//for example
print(address["city"] ?? "")
}
//or id
print(data["id"] ?? "")
//username
print(data["username"] ?? "")
}
Solution 2
Alper, why don't you use SwiftyJSON to do this. Download the cocoa pod and follow instructions on their Github page: https://github.com/SwiftyJSON/SwiftyJSON
Parsing then becomes very simple. It would appear that in Swift 4, JSON is handled much better and libraries like SwiftyJSON won't be required.
Alper
Updated on July 24, 2022Comments
-
Alper almost 2 years
I am a newbie to parsing JSON and using Restful API. Whatevs, i have been looking a lot for this issue and I found lots of. But I couldn't figure it out.
JSON that I want to parse is: http://jsonplaceholder.typicode.com/users
guard let url = URL(string: "http://jsonplaceholder.typicode.com/users/") else {return} let session = URLSession.shared session.dataTask(with: url) { (data, response, error) in if error != nil { print(error ?? "") } if data != nil { do{ let json = try JSONSerialization.jsonObject(with: data!, options: .mutableLeaves) guard let idk = json as? [Dictionary<String, Any>] else {return} print(idk) } catch{ print(error) } } }.resume()
I came untill here and I can't move on. For example I'd like to reach id, name and username but I dont know what to do anymore. And Im wonder what if I'd like to dive into the dictionary of Adress ?
-
Alper almost 7 yearsWell Im known about SwiftyJSON and Alamofire but Im trying to understand the logic of parsing JSON. For example array of dictionaries, only dicitonaries, dicitonaries of dictionaries im trying to understand how to use them.
-
Alper almost 7 yearsThis is worked for me and I got the logic. But data: Dictionary<String, Any> what happens in here? I deleted this line and it still worked?
-
Vasil Hristov almost 7 yearsIt is like a definition helper for the compiler, but it isn't required.
-
Alper almost 7 yearsWhat would happen if address dictionary was an array? What should I use instead of Dictionary<String, Any> ?
-
Vasil Hristov almost 7 yearsYou have to use [Dictionary<String, Any>] in this case