Search code examples
iosjsonswiftnsdictionary

how to parse JSON data from local files?


I am very new to JSON parsing and tried to parse a JSON file which has list of cars but when I do parse, it gives out nil:

    func jsonTwo(){
    let url = Bundle.main.url(forResource: "car_list", withExtension: "json")!
    let data = try! Data(contentsOf: url)
    let JSON = try! JSONSerialization.jsonObject(with: data, options: []) as? [String : Any]
    print(".........." , JSON , ".......")
    let brand = JSON?["models"] as? [[String : Any]]
    print("=======",brand,"=======")
}

and when I made some modifications to this code as below:

    func jsonTwo(){
    let url = Bundle.main.url(forResource: "car_list", withExtension: "json")!
    let data = try! Data(contentsOf: url)
    let JSON = try! JSONSerialization.jsonObject(with: data, options: []) 
    print(".........." , JSON , ".......")
    let brand = JSON["brand"] as? [[String : Any]]
    print("=======",brand,"=======")
}

then I get and error saying:

"Type 'Any' has no subscript members"

below is a sample of the JSON file that I am using

[{"brand": "Aston Martin", "models": ["DB11","Rapide","Vanquish","Vantage"]}]


Solution

  • Please note that variable JSON in your code is an array of objects. You have to cast it properly.

    func jsonTwo(){
        let url = Bundle.main.url(forResource: "car_list", withExtension: "json")!
        let data = try! Data(contentsOf: url)
        let JSON = try! JSONSerialization.jsonObject(with: data, options: []) 
        print(".........." , JSON , ".......")
        if let jsonArray = JSON as? [[String: Any]] {
            for item in jsonArray {
                let brand = item["brand"] as? String ?? "No Brand" //A default value
                print("=======",brand,"=======")
            }
        }
    }