Swift
JSON
data parsing
programming
tutorial

How to parse a JSON file in swift?

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

The standard Swift way to parse a JSON file is to load the file into Data and decode it with JSONDecoder. For most app code, Codable models are the cleanest and safest approach because they give you typed parsing instead of loose dictionary access.

Define a decodable model first

Parsing gets much easier when the JSON shape is expressed as Swift types.

swift
1import Foundation
2
3struct User: Codable {
4    let id: Int
5    let name: String
6    let isAdmin: Bool
7}
8
9let json = """
10[
11  { "id": 1, "name": "Ada", "isAdmin": true },
12  { "id": 2, "name": "Grace", "isAdmin": false }
13]
14"""
15
16let data = Data(json.utf8)
17let users = try JSONDecoder().decode([User].self, from: data)
18print(users)

This example parses an in-memory JSON string, but the same decoding step is used for a real file once you load the file contents into Data.

Parsing a local JSON file

If the file is bundled with the app, find its URL through Bundle.main, read the data, and decode it.

swift
1import Foundation
2
3struct Config: Codable {
4    let apiBaseURL: String
5    let retryCount: Int
6}
7
8func loadConfig() throws -> Config {
9    guard let url = Bundle.main.url(forResource: "config", withExtension: "json") else {
10        throw NSError(domain: "Example", code: 1, userInfo: [NSLocalizedDescriptionKey: "Missing file"])
11    }
12
13    let data = try Data(contentsOf: url)
14    return try JSONDecoder().decode(Config.self, from: data)
15}

This is the standard pattern for app-bundled JSON fixtures, configuration, or seed data.

Handling keys that do not match Swift property names

Real JSON often uses snake_case while Swift properties use camelCase. CodingKeys lets you map them explicitly.

swift
1import Foundation
2
3struct Post: Codable {
4    let postID: Int
5    let authorName: String
6
7    enum CodingKeys: String, CodingKey {
8        case postID = "post_id"
9        case authorName = "author_name"
10    }
11}

This keeps the Swift API clean without forcing the JSON source to change.

Error handling matters

When JSON decoding fails, the problem is often structural: wrong key names, wrong types, or an unexpected array-versus-object mismatch. Handle these failures explicitly and inspect the thrown decoding error instead of assuming the file is malformed in some vague way.

It is also worth keeping file loading and JSON decoding conceptually separate. One error means the file could not be found or read. The other means the file existed but did not match the model you described.

That separation makes debugging far faster.

When not to use loose dictionaries

Swift can parse JSON into [String: Any] with JSONSerialization, but that is usually a weaker option for ordinary application models. It gives you manual casting, more runtime checks, and fewer compiler guarantees.

JSONSerialization is still useful for highly dynamic payloads, but typed Codable models are the better default when the JSON shape is known.

Common Pitfalls

  • Trying to parse JSON before deciding whether the top-level type is an array or an object.
  • Using property names that do not match JSON keys without CodingKeys or a decoder strategy.
  • Treating file-loading errors and decoding errors as if they were the same problem.
  • Reaching for [String: Any] when the JSON structure is stable and strongly typed.
  • Forgetting that Data(contentsOf:) can throw if the file URL is wrong or unreadable.

Summary

  • In Swift, parse JSON files by loading Data and decoding with JSONDecoder.
  • 'Codable models are the cleanest default for known JSON structures.'
  • Use Bundle.main.url(forResource:withExtension:) for bundled JSON files.
  • Add CodingKeys when JSON keys and Swift property names differ.
  • Separate file I/O errors from decoding errors so debugging stays clear.

Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.