parse json file in swift

To parse a JSON file in Swift, you can use the JSONDecoder class.

First, you need to create a struct or class that represents the data in your JSON file. Let's say you have a JSON file containing information about cars, with each car having a make, model, and year:

main.swift
struct Car: Codable {
    let make: String
    let model: String
    let year: Int
}
85 chars
6 lines

Then you can use the JSONDecoder to decode the JSON data into an array of Car objects:

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

let url = URL(fileURLWithPath: path)

do {
    let data = try Data(contentsOf: url)
    let decoder = JSONDecoder()
    let cars = try decoder.decode([Car].self, from: data)
    // do something with the cars array
} catch {
    print("Error decoding JSON: \(error)")
}
357 chars
13 lines

In this example, we first get the path to the JSON file using Bundle.main.path(forResource:ofType:). Then we create a URL object from the path, and use it to load the data from the JSON file using Data(contentsOf:).

Next, we create a JSONDecoder object, and use it to decode the JSON data into an array of Car objects using decode(_:from:). If there are any errors during decoding, we catch them and print an error message.

Now you can do something with the cars array, such as displaying them in a table view or sorting them by year.

related categories

gistlibby LogSnag