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.swift85 chars6 lines
Then you can use the JSONDecoder
to decode the JSON data into an array of Car
objects:
main.swift357 chars13 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.
gistlibby LogSnag