Add JSON file to Swift Playgrounds

3.4k Views Asked by At

I've created a playground book on swift playgrounds, but I don't know how to add a JSON file to the directory. Can you add JSON files to swift playgrounds (ipad)? If so, how?

1

There are 1 best solutions below

0
Vinayaka S Yattinahalli On

Click on the '+' icon on the top right corner of the swift Playgrounds and choose the json file by clicking Insert from... option. Then use the below code to read the data from json file.

import Foundation

do {
    guard let fileUrl = Bundle.main.url(forResource: "filename", withExtension: "json") else { fatalError() }
    let text = try String(contentsOf: fileUrl, encoding: String.Encoding.utf8)
    print(text)
} catch {
    print(error)
}