Hanzla Rafique
Hanzla Rafique

Reputation: 63

Fetch and Check internal (Local) JSON file in swift

I want to check city name From local JSON if found then massage show "You got it". But one problem came occurred that is I fetch data from file is successfully but I'd know how to compare it.

Here is my JSON file look like:

{
  "data": [
    {
      "zip_code": 55001,
      "latitude": 44.90717,
      "longitude": -92.816193,
      "city": "Afton",
      "state": "MN",
      "county": "Washington"
    },
    {
      "zip_code": 55002,
      "latitude": 45.513447,
      "longitude": -92.894239,
      "city": "Almelund",
      "state": "MN",
      "county": "Chisago"
    }
   ]
}

Code is here:

func FatchingInformation(){


        do {
            if let file = Bundle.main.url(forResource: "Zone", withExtension: "json") {
                let data = try Data(contentsOf: file)
                let json = try JSONSerialization.jsonObject(with: data, options: [])
                if let object = json as? [String: Any] {
                    // This condition work and Get JSON on Debug Area 
                    print("Obj is ::: \(object)")

                } else if let object = json as? [Any] {
                    // json is an array
                    print("Object is \(object)")
                } else {
                    print("JSON is invalid")
                }
            } else {
                print("no file")
            }
        } catch {
            print(error.localizedDescription)
        }
        }

Upvotes: 0

Views: 226

Answers (2)

Anbu.Karthik
Anbu.Karthik

Reputation: 82759

you are in right way on your JSON is dict of array of dictionary, you need to iterate your [String: Any] first there after check it contains array or dict then you need to follow as below

if let object = json as? [String: Any], let objectArray = object["data"] as?  [[String: Any]]  {
 // do stuff
 for getDictItems in objectArray{
   if let getCityCompare = getDictItems["city"] as? String, !getCityCompare.isEmpty, getCityCompare == "Almelund"{
    print("city name  is \(getCityCompare)")
    break
  }
 }
}

Upvotes: 1

Jawad Ali
Jawad Ali

Reputation: 14397

You ca use decodable Struct to decode json

// MARK: - Address
struct Address: Codable {
    let data: [Datum]
}

// MARK: - Datum
struct Datum: Codable {
    let zipCode: Int
    let latitude, longitude: Double
    let city, state, county: String

    enum CodingKeys: String, CodingKey {
        case zipCode = "zip_code"
        case latitude, longitude, city, state, county
    }
}

let address = try? JSONDecoder().decode(Address.self, from: jsonData)

Upvotes: 0

Related Questions