How to Read & Parse local JSON file in Swift

Today, we will learn how to read the JSON file from your project file system & parse the content using JSONDecoder class. Of course, we are going to show the results in the basic table view.

readLocalJSONFile function will take the file name as input & return contents as a Data object.

  • First, we need to find the file path in the bundle. So we are using Bundle.main.path method to get the file path.
  • If the file path exits, we are going to convert the file path as URL.
  • Now we are passing fileUrl to Data contentsOf method. This will read the entire data at path & return it as a data object.

The returned data object is not readable. We should parse the data object to see it in a readable format. Before parsing we should create the model object similar to our local JSON format.

struct user: Codable {
let userId: Int
let firstName: String
let lastName: String
let phoneNumber: String
let emailAddress: String
struct sampleRecord: Codable {
let users: [user]

Our model class structure should be similar to our local JSON file format.

Here is our parse function. We have to pass the data object received from the previous function. Here we are using the JSONDecoder decode method to convert data objects to a readable format.

How to use it?

let jsonData = readLocalJSONFile(forName: "SampleRecords")if let data = jsonData {
if let sampleRecordObj = parse(jsonData: data) {
//You can read sampleRecordObj just like below.
print("users list: \(sampleRecordObj.users)")
print("firstName:\(sampleRecordObj.users.first?.firstName ?? "")")

Thanks you for reading 🙏

If you like the article Clap it !! 👏👏

Engineer, Traveller & Dreamer