Knowband Blog | Ecommerce Modules

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 giving 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 the 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
    }

<strong>Recommended Read: </strong><a href="https://www.knowband.com/blog/tutorials/iterate-element-json-string-android-ios/">Iterate through each element of JSON string in Android and iOS</a>

Recommended Read: How to Migrate Magento Store From Localhost To Server?