← back to the blog


How to open and parse JSON file/data in Swift 5.1

Posted on December 1st, 2019 in Swift by George

 

Code exampled.

Follow the comments in code, please.


//get the path to the txt file 

guard let path = Bundle.main.path(forResource: "addressesAPI", ofType: "txt") else { return } 

// generate and URL object using path above

let url = URL(fileURLWithPath: path);

do {
  let data = try Data(contentsOf: url)
  let json = try JSONSerialization.jsonObject(width: data, options: .mutableContainer)
  
  print(json);
 
 // attempt to cast json data to an array
  guard let array = json as? [Any] else { return }
  

 // iterate the array elements and extract the desired data 
  for item in array {
    guard let addressDict = item as? [String: Any] else { return }
    guard let addressId = addressDict["id"] as? Int else { print("not an Int"); return }
    guard let addressPostcode = addressDict["postcode"] as? String else { return }
    
    // you can deal with nested Dictionaries as bellow
    
    guard let company = addressDict["company"] as? [String: String] else { return }
    guard let companyName = company["name"] else { return }

                print(addressId)
                print(addressPostcode)
                print(companyName)
                print(" ") 
   }
  
} catch {
  print(error)
}

 

Thank you!