Quantcast
Channel:
Viewing all articles
Browse latest Browse all 27

Load JSON from file/URL in Swift 3

$
0
0

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
    }
  }

Viewing all articles
Browse latest Browse all 27

Trending Articles