Jennifer
Jennifer

Reputation: 1852

Correct way to place and handle .json file in Xcode

I just started to learn Swift and xcode and the first problem that I'm facing is how and where should I place the json file ? And how to use those files? Should I place the .json files within Assets folder ? Since I find it difficult, I would love to hear some tips or examples from you !

Upvotes: 22

Views: 39713

Answers (5)

Henry Noon
Henry Noon

Reputation: 403

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

Upvotes: 17

Sukhdeep Singh Kalra
Sukhdeep Singh Kalra

Reputation: 827

Please review the below image to check where to place the file. I suggest you to create a group and add the file in that.enter image description here

After that, review the below could for using that file.

Edit: This is the updated code for Swift 5 if that helps anyone.

    let path = Bundle.main.path(forResource: "filename", ofType: "json")
    let jsonData = try? NSData(contentsOfFile: path!, options: NSData.ReadingOptions.mappedIfSafe)

Upvotes: 8

Denis Kutlubaev
Denis Kutlubaev

Reputation: 16124

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

Upvotes: 28

Abhooshan Bhattarai
Abhooshan Bhattarai

Reputation: 151

var location = "test"
var fileType = "json"
if let path = Bundle.main.path(forResource: location, ofType: fileType) {
        do {
            let data = try Data(contentsOf: URL(fileURLWithPath: path), options: .alwaysMapped)
            let jsonObj = JSON(data: data)
            if jsonObj != JSON.null {
            }
        } catch let error {
            print(error.localizedDescription)
        }}

Upvotes: 4

Sukhdeep Singh Kalra
Sukhdeep Singh Kalra

Reputation: 827

As per your requirement, you want to read json from that json file.

I am using SWIFTY JSON Library for that.

Find below the link for that

https://github.com/SwiftyJSON/SwiftyJSON

Add this library to your project.

After adding it, now review the below code:-

let json = JSON(data: jsonData!)
for (index, subjson): (String, JSON) in json{
    let value = subjson["key"].stringValue
}

Upvotes: 0

Related Questions