Correct way to place and handle .json file in Xcode

How I've done this in September 2019...

1) In Xcode, create an Empty file. Give the file a .json suffix

2) Type in or paste in your JSON

3) Click Editor -> Syntax Coloring -> JSON

4) Inside the file, highlight the JSON, click ctrl + i to indent

5) import SwiftyJSON using Cocoapods

6) In your ViewController, write...

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

let url = URL(fileURLWithPath: path)

do {  

    let data = try Data(contentsOf: url)

    let json = try JSON(data: data)

} catch {

    print(error)
}

N.B. - "File" is the name of the file you created, but excluding the .json suffix

See SwiftyJSON GitHub page for more info - https://github.com/SwiftyJSON/SwiftyJSON


You can add an empty file, select syntax coloring as JSON and paste your json text. Even if it is not formatted, you can format it by selecting all the text and pressing Ctrl + I.

enter image description here

Tags:

Json

Xcode

Swift