user9328598
user9328598

Reputation:

How to get data from local JSON file in swift?

I want to get data from local JSON file. It's look like:

[
[
{
  "link": "link1",
  "answers": [
    "answer1",
    "answer2",
    "answer3",
    "answer4",
    "answer5"
  ],
  "questions": "question1"
},
{
  "link": "link2",
  "answers": [
    "answer1",
    "answer2",
    "answer3",
    "answer4",
    "answer5"
  ],
  "questions": "question2"
}
]
]

How can I take separately each element? And how can I take separately each answer? I want to use answers in table view. indexPath.row[1] = answer1 indexPath.row[2] = answer2...

let url = Bundle.main.url(forResource: "info", withExtension: "json")!
    do {
        let jsonData = try Data(contentsOf: url)
        let json = try JSONSerialization.jsonObject(with: jsonData)
        print(json)

        //let current = json["title"] as! [String: [String:Any]]

        //for (key, currency) in current {
            //let quest = currency["title"] as! String
            //let img = currency["image"] as! String
            //let ans = currency["answers"] as! [String]
        //}
    }
    catch {
        print(error)
    }

}

Upvotes: 0

Views: 13570

Answers (1)

Kamran
Kamran

Reputation: 15248

You have to take care of the JSON structure to get the correct values. See the below snippet to see how you can reach your questions in JSON.

    let url = Bundle.main.url(forResource: "File", withExtension: "txt")!
    do {
        let jsonData = try Data(contentsOf: url)
        let json = try JSONSerialization.jsonObject(with: jsonData) as! [[[String: Any]]]

        if let question1 = json.first?[0] {
            print( question1["link"] as! String)
        }

        if let question2 = json.first?[1] {
            print( question2["link"] as! String)
        }
    }
    catch {
        print(error)
    }

So now, you know how to reach the actual data. You should create some Question class. Then you should retain a list of questions parsed from the file and use that list for your TableView.

Upvotes: 3

Related Questions