parse json file in swift in swift

To parse a JSON file in Swift, we can use the Codable protocol provided by Swift standard library's Foundation framework. Here's an example:

Assuming we have a JSON file data.json that contains the following data:

{
  "name": "John Doe",
  "age": 30,
  "email": "john.doe@example.com"
}
73 chars
6 lines

We can define a struct that conforms to the Codable protocol, with properties matching the keys in the JSON data:

main.swift
struct Person: Codable {
    let name: String
    let age: Int
    let email: String
}
87 chars
6 lines

To parse the JSON file into an instance of our Person struct, we can use a JSONDecoder and read the contents of the file into a Data object:

main.swift
let decoder = JSONDecoder()
let url = Bundle.main.url(forResource: "data", withExtension: "json")!
let data = try! Data(contentsOf: url)
let person = try! decoder.decode(Person.self, from: data)
195 chars
5 lines

In the above example, we first create a JSONDecoder instance, then retrieve the URL of our data.json file using the Bundle API. We then read the contents of that file into a Data object using the contentsOf method of the Data class. Finally, we decode the JSON data using the decode method of the JSONDecoder class and our Person struct as the generic parameter.

We can now access the properties of the parsed person object:

main.swift
print(person.name) // "John Doe"
print(person.age) // 30
print(person.email) // "john.doe@example.com"
103 chars
4 lines

gistlibby LogSnag