How to Read data from local JSON file in Swift?

Introduction

We will assume that we want to have a JSON file added inside our project and want to access its data in swift language.

Code

You can create a JSON file in Xcode by going to File > New File > Empty and give the file any name (eg. example.json). The file will be added and then we can add a JSON String in the file. i.e. –

{“animal”:”Lion”, “bird”:”Sparrow”}

You can add the above-mentioned String directly into the JSON file that we created.

The following function can be used to read the JSON data from JSON file so that it can be accessed in Swift –

  static func readJSONFromFile(fileName: String) -> Any?
    {
        var json: Any?
        if let path = Bundle.main.path(forResource: fileName, ofType: "json") {
            do {
                let fileUrl = URL(fileURLWithPath: path)
                // Getting data from JSON file using the file URL
                let data = try Data(contentsOf: fileUrl, options: .mappedIfSafe)
                json = try? JSONSerialization.jsonObject(with: data)
            } catch {
                // Handle error here
            }
        }
        return json
    }

Leave a Reply

Your email address will not be published. Required fields are marked *