Parsing JSON Array of Dictionaries

10,229

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.

Share:
10,229
Alper
Author by

Alper

Updated on July 24, 2022

Comments

  • Alper
    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
    Alper almost 7 years
    Well 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
    Alper almost 7 years
    This 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
    Vasil Hristov almost 7 years
    It is like a definition helper for the compiler, but it isn't required.
  • Alper
    Alper almost 7 years
    What would happen if address dictionary was an array? What should I use instead of Dictionary<String, Any> ?
  • Vasil Hristov
    Vasil Hristov almost 7 years
    You have to use [Dictionary<String, Any>] in this case