How to Read a JSON File in Swift: A Comprehensive Guide

How to Read a JSON File in Swift: A Comprehensive Guide

28 February 2025 Stephan Petzl Leave a comment Xcode

Working with JSON files in Swift can be a daunting task, especially for beginners. This guide will walk you through the process of reading a JSON file using Swift, providing clear instructions and examples to help you master this essential skill.

Understanding JSON Files

JSON (JavaScript Object Notation) is a lightweight data interchange format that is easy for humans to read and write, and easy for machines to parse and generate. In Swift, reading JSON files typically involves loading the file into memory and then using a JSON decoder to convert the data into a usable format.

Step-by-Step Guide to Reading JSON Files

1. Set Up Your JSON File

Ensure your JSON file, for example, test.json, is added to your project resources. It should be structured correctly, like this:

{
  "person": [
    {
      "name": "Bob",
      "age": "16",
      "employed": "No"
    },
    {
      "name": "Vinny",
      "age": "56",
      "employed": "Yes"
    }
  ]
}

2. Define Your Swift Structures

Create Swift structures that match the JSON data structure. Here’s an example:

struct ResponseData: Decodable {
    var person: [Person]
}

struct Person: Decodable {
    var name: String
    var age: String
    var employed: String
}

3. Load and Decode the JSON File

Use the following Swift function to load the JSON file and decode it into your Swift structures:

func loadJson(filename fileName: String) -> [Person]? {
    if let url = Bundle.main.url(forResource: fileName, withExtension: "json") {
        do {
            let data = try Data(contentsOf: url)
            let decoder = JSONDecoder()
            let jsonData = try decoder.decode(ResponseData.self, from: data)
            return jsonData.person
        } catch {
            print("Error: \(error)")
        }
    }
    return nil
}

Example Usage

To use this function, simply call it with the name of your JSON file (without the extension) as an argument:

if let persons = loadJson(filename: "test") {
    for person in persons {
        print("Name: \(person.name), Age: \(person.age), Employed: \(person.employed)")
    }
}

Enhancing Your Workflow with Repeato

While reading JSON files is a crucial task in Swift development, automating tests for your applications can significantly enhance your workflow. Repeato, our no-code test automation tool, can assist you with this. It allows you to create, run, and maintain automated tests for iOS, Android, and web apps efficiently. With Repeato, you can quickly record tests using a test recorder, and its support for data-driven testing ensures your JSON file operations are thoroughly tested. Learn more about how Repeato can streamline your testing process in our documentation.

Like this article? there’s more where that came from!