Load JSON from file/URL in Swift 3

Load JSON from file/URL in Swift 3

onedayitwillmake No Comment

Simple snippet to load JSON into from a filepath or URL

// Retrieves JSON from bundle
  private func loadJSON(fileURL:URL)->[String : Any]? {
    // Parse the JSON
    do {
      // Create a string out of the file contents
      let contents = try String(contentsOf: fileURL) // use contentsOfFile for strings
      // Turn it into data to feed JSONSerialization class
      let data     = contents.data(using: String.Encoding.utf8)
      // Attempt to turn it into JSON, or show error
      let json:[String:Any]? = try? JSONSerialization.jsonObject(with: data!, options: []) as! [String : Any]
      return json
    } catch {
      Swift.print("Error parsing json")
      return nil

Leave a Reply