Swift example

How to parse JSON into a struct in Swift

10 min read Updated Dec 2026 Runs in an isolated runtime
Quick answer

Declare a struct that conforms to Decodable, with property names that match the JSON keys, and decode it with JSONDecoder: let user = try JSONDecoder().decode(User.self, from: Data(json.utf8)). It lives in Foundation, works for nested structs and arrays ([User].self), and throws a DecodingError when a key is missing or a value has the wrong type.

Since Swift 4, the standard way to read JSON is Codable: you describe the shape as plain structs, the compiler writes the decoding code, and JSONDecoder fills them in. Codable is Decodable (read) plus Encodable (write); for parsing, Decodable is enough. The sections below cover the basic decode, keys that don't match your property names and properties you want to skip, missing keys and default values, enums and readable errors, dates and reading a JSON file, and the untyped route to a [String: Any] dictionary, then a table to pick from. Each example runs on this page: hit Run, then edit the code and run it again.

1Decodable and JSONDecoderRecommended

Mark the struct Decodable and give it one property per JSON key you want, with the matching Swift type: String, Int, Double, Bool, arrays, and other Decodable structs for nested objects. A key that may be absent or null gets an optional type. JSONDecoder reads Data, not a String, so convert the text with Data(json.utf8). The #"…"# raw strings below let the JSON keep its quotes without escaping. A JSON array at the top level decodes as an array of your type.

decode.swift
import Foundation

struct Address: Decodable {
    let city: String
    let zip: String
}

struct User: Decodable {
    let id: Int
    let name: String
    let email: String?      // optional: the key may be missing or null
    let tags: [String]
    let address: Address    // a nested object is another Decodable struct
}

let json = #"{"id": 7, "name": "Ada", "role": "owner","#
    + #" "tags": ["admin", "beta"], "address": {"city": "London", "zip": "N1"}}"#

do {
    let user = try JSONDecoder().decode(User.self, from: Data(json.utf8))
    print(user.name, user.id)
    print(user.tags)
    print(user.address.city)
    print(user.email ?? "no email")
} catch {
    print("decode failed:", error)
}

// A JSON array at the top level decodes as [User]
let list = #"[{"id": 1, "name": "Ada", "tags": [], "#
    + #""address": {"city": "London", "zip": "N1"}},"#
    + #" {"id": 2, "name": "Linus", "email": "[email protected]", "tags": [], "#
    + #""address": {"city": "Portland", "zip": "97201"}}]"#

do {
    let users = try JSONDecoder().decode([User].self, from: Data(list.utf8))
    for user in users {
        print(user.id, user.name, user.email ?? "-", user.address.city)
    }
} catch {
    print("decode failed:", error)
}

Output

The struct comes back fully typed: Ada 7, the tags as a real [String], and London read through the nested Address. The JSON has no email key, so the optional is nil and prints no email. The extra role key is ignored: JSONDecoder only reads the keys your type asks for, so an API can add fields without breaking your app. The array decodes with [User].self and prints one line per user. decode throws, so it always sits in do/catch (or in a function marked throws); section 4 turns the error into a readable message.

2Renaming keys and excluding properties with CodingKeys

When the JSON says user_id and you want id, add a nested CodingKeys enum: one case per property that takes part in coding, with the JSON name as the raw value where it differs. The same enum excludes properties: a property with no case is never read from or written to JSON, as long as it has a default value. If the API simply uses snake_case everywhere, skip the enum and set keyDecodingStrategy = .convertFromSnakeCase, which turns user_id into userId for every key.

coding_keys.swift
import Foundation

let json = #"{"user_id": 42, "full_name": "Ada Lovelace", "is_admin": true}"#
let data = Data(json.utf8)

// CodingKeys: map each property to its JSON key
struct User: Codable {
    let id: Int
    let name: String
    let isAdmin: Bool
    var isSelected = false  // no case below: never decoded or encoded

    enum CodingKeys: String, CodingKey {
        case id = "user_id"
        case name = "full_name"
        case isAdmin = "is_admin"
    }
}

let user = try JSONDecoder().decode(User.self, from: data)
print(user.id, user.name, user.isAdmin, user.isSelected)

// Encoding uses the same keys, and leaves isSelected out
let encoder = JSONEncoder()
encoder.outputFormatting = .sortedKeys
print(String(decoding: try encoder.encode(user), as: UTF8.self))

// convertFromSnakeCase: user_id -> userId, no CodingKeys needed
struct Account: Decodable {
    let userId: Int
    let fullName: String
    let isAdmin: Bool
}

let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
let account = try decoder.decode(Account.self, from: data)
print(account.userId, account.fullName, account.isAdmin)

Output

42 Ada Lovelace true false: the three renamed keys are read, and isSelected keeps its default. Encoding the same value back writes user_id, full_name and is_admin and no isSelected at all (.sortedKeys just makes the order stable). Leave the default off an excluded property and the build fails with type 'User' does not conform to protocol 'Decodable', plus a note that it does not have a matching CodingKey and does not have a default value. One trap with .convertFromSnakeCase: user_id becomes userId, so a property named userID is not found; name it userId or use CodingKeys.

3Missing keys: optionals and default values

The synthesized decoder requires every non-optional property's key, and a default value on the property doesn't change that: var fontSize = 14 still throws keyNotFound when the key is absent. You have two choices. Make the property optional, which reads a missing key or null as nil. Or write init(from:) yourself and use decodeIfPresent, which returns an optional, with ?? to put the default in. Once you write the initializer, the CodingKeys enum is yours to declare too.

defaults.swift
import Foundation

struct Settings: Decodable {
    let theme: String
    let fontSize: Int
    let autosave: Bool
    let nickname: String?

    enum CodingKeys: String, CodingKey {
        case theme, fontSize, autosave, nickname
    }

    // A missing key (or null) falls back to a default instead of throwing
    init(from decoder: any Decoder) throws {
        let c = try decoder.container(keyedBy: CodingKeys.self)
        theme = try c.decodeIfPresent(String.self, forKey: .theme) ?? "light"
        fontSize = try c.decodeIfPresent(Int.self, forKey: .fontSize) ?? 14
        autosave = try c.decodeIfPresent(Bool.self, forKey: .autosave) ?? true
        nickname = try c.decodeIfPresent(String.self, forKey: .nickname)
    }
}

let inputs = [
    #"{"theme": "dark", "fontSize": 18, "autosave": false}"#,
    #"{"fontSize": 12}"#,
    #"{}"#,
    #"{"theme": null, "nickname": "ada"}"#,
    #"{"fontSize": "big"}"#,
]

for json in inputs {
    do {
        let s = try JSONDecoder().decode(Settings.self, from: Data(json.utf8))
        print(s.theme, s.fontSize, s.autosave, s.nickname ?? "-")
    } catch DecodingError.typeMismatch(let type, let context) {
        let key = context.codingPath.last?.stringValue ?? "?"
        print("wrong type for \(key), expected \(type)")
    } catch {
        print("other error:", error)
    }
}

// A default on the property alone is not enough
struct Strict: Decodable {
    var theme = "light"
    var fontSize = 14
}

do {
    let s = try JSONDecoder().decode(Strict.self,
                                     from: Data(#"{"theme": "dark"}"#.utf8))
    print(s.theme, s.fontSize)
} catch DecodingError.keyNotFound(let key, _) {
    print("missing key:", key.stringValue)
} catch {
    print("other error:", error)
}

Output

A full object decodes as written (dark 18 false -), a partial one fills the gaps (light 12 true -), and even {} works. A null counts as missing for decodeIfPresent, so "theme": null gives light. A key that is there with the wrong type still throws, which is what you want: wrong type for fontSize, expected Int. The last struct shows the surprise behind the Stack Overflow question: both properties have defaults, yet the decode fails with missing key: fontSize. With many fields, a small extension on KeyedDecodingContainer that wraps decodeIfPresent(...) ?? value keeps each line short.

4Decodable enums and readable errors

An enum with a String (or Int) raw type becomes Decodable just by saying so: the JSON value must equal one of the raw values. A value the enum doesn't know makes the whole decode throw. For fields that can grow on the server side, write a small init(from:) that reads the string from a singleValueContainer and maps anything unknown to a fallback case. When a decode does fail, the DecodingError cases carry the key and the codingPath, which is enough for a one-line message.

enums_errors.swift
import Foundation

// A String raw-value enum is Decodable with no extra code
enum Status: String, Decodable {
    case active, suspended
    case pendingReview = "pending_review"
}

// Same idea, but an unknown value becomes .unknown instead of throwing
enum Plan: String, Decodable {
    case free, pro
    case unknown

    init(from decoder: any Decoder) throws {
        let raw = try decoder.singleValueContainer().decode(String.self)
        self = Plan(rawValue: raw) ?? .unknown
    }
}

struct Account: Decodable {
    let name: String
    let status: Status
    let plan: Plan
}

// Turn a DecodingError into one readable line
func describe(_ error: any Error) -> String {
    guard let error = error as? DecodingError else {
        return "\(error)"
    }
    func path(_ c: DecodingError.Context) -> String {
        let keys = c.codingPath.map(\.stringValue).joined(separator: ".")
        return keys.isEmpty ? "the top level" : keys
    }
    switch error {
    case .keyNotFound(let key, let c):
        return "missing key '\(key.stringValue)' at \(path(c))"
    case .valueNotFound(_, let c):
        return "null value at \(path(c))"
    case .typeMismatch(let type, let c):
        return "expected \(type) at \(path(c))"
    case .dataCorrupted(let c):
        return "bad data at \(path(c)): \(c.debugDescription)"
    @unknown default:
        return "\(error)"
    }
}

let inputs = [
    #"{"name": "Ada", "status": "pending_review", "plan": "pro"}"#,
    #"{"name": "Bob", "status": "active", "plan": "enterprise"}"#,
    #"{"name": "Cy", "status": "deleted", "plan": "free"}"#,
    #"{"name": "Di", "status": 3, "plan": "free"}"#,
    #"{"name": "Ed", "status": null, "plan": "free"}"#,
    #"{"name": "Fay", "plan": "free"}"#,
    #"{"name": "Gus", "status": "active""#,
]

for json in inputs {
    do {
        let a = try JSONDecoder().decode(Account.self, from: Data(json.utf8))
        print("\(a.name): \(a.status) (\(a.status.rawValue)), plan \(a.plan)")
    } catch {
        print(describe(error))
    }
}

Output

"pending_review" maps to the case pendingReview through its raw value, and Bob's "enterprise" plan lands on unknown instead of failing. Status has no fallback, so "deleted" throws dataCorrupted with the message Cannot initialize Status from invalid String value deleted. The other lines show the remaining cases: a number where a string belongs (typeMismatch), null for a non-optional (valueNotFound), a missing key, and broken JSON. A plain print(error) on the toolchain here gives DecodingError.dataCorrupted: Data was corrupted. Path: status. Debug description: …, and older Swift versions print the raw enum and its Context. Avoid error.localizedDescription for these: on Linux here it is just The operation could not be completed. The data isn’t in the correct format., with no key and no path.

5Reading a JSON file, with dates

To parse a file, read its bytes with Data(contentsOf:) and decode those; the decoding part doesn't change. The example first writes a small file into the working directory, so it has one to read. In an iOS or macOS app, a file you ship with the app comes from the bundle instead: Bundle.main.url(forResource: "events", withExtension: "json") returns its URL (or nil if it isn't in the target). JSON has no date type, so dates arrive as strings or numbers; set dateDecodingStrategy = .iso8601 to decode strings like 2026-12-01T09:30:00Z straight into Date properties.

read_file.swift
import Foundation

struct Event: Decodable {
    let title: String
    let startsAt: Date
}

// Set up: write a JSON file into the working directory
let url = URL(fileURLWithPath: "events.json")
let text = #"[{"title": "Launch", "startsAt": "2026-12-01T09:30:00Z"},"#
    + #" {"title": "Retro", "startsAt": "2026-12-04T16:00:00+01:00"}]"#
try text.write(to: url, atomically: true, encoding: .utf8)

// Read the file's bytes, then decode them
do {
    let data = try Data(contentsOf: url)
    let decoder = JSONDecoder()
    decoder.dateDecodingStrategy = .iso8601
    let events = try decoder.decode([Event].self, from: data)
    for event in events {
        print(event.title, event.startsAt)
    }
} catch {
    print("could not load events:", error)
}

// A missing file throws before any decoding happens
do {
    _ = try Data(contentsOf: URL(fileURLWithPath: "missing.json"))
} catch CocoaError.fileReadNoSuchFile {
    print("no such file: missing.json")
} catch {
    print("read failed:", error)
}

Output

Both events decode with real Date values. A Date prints in UTC, so Retro's 16:00:00+01:00 shows as 2026-12-04 15:00:00 +0000: the same moment, written in a different zone. A path that doesn't exist throws CocoaError.fileReadNoSuchFile, caught here before any JSON is touched, so you can tell "no file" apart from "bad JSON". Without a date strategy, JSONDecoder expects a number of seconds since 1 January 2001 and fails on strings. For other date formats, use .formatted(formatter) with a DateFormatter, or .custom with your own parsing code.

6A JSON string to a dictionary with JSONSerialization

When you don't know the shape ahead of time, or you only need one or two values from a large payload, JSONSerialization.jsonObject(with:) parses JSON into Foundation types: a dictionary for an object, an array for an array. Cast the result to [String: Any], then cast each value to the type you expect with as?. Two things to keep in mind: a Swift dictionary has no fixed order, so sort the keys before printing or comparing; and when every value has the same type, JSONDecoder can decode straight into [String: Int] with no casting.

to_dictionary.swift
import Foundation

let json = #"{"name": "Ada", "age": 36, "langs": ["en", "fr"],"#
    + #" "address": {"city": "London"}, "spouse": null}"#

do {
    let object = try JSONSerialization.jsonObject(with: Data(json.utf8))
    if let dict = object as? [String: Any] {
        // A dictionary has no fixed order: sort the keys to print it
        print(dict.keys.sorted())

        // Every value is Any: cast each one to the type you expect
        let name = dict["name"] as? String ?? "?"
        let age = dict["age"] as? Int ?? 0
        let langs = dict["langs"] as? [String] ?? []
        let address = dict["address"] as? [String: Any]
        let city = address?["city"] as? String ?? "-"
        print(name, age + 1, langs, city)

        // JSON null is NSNull, not nil; a missing key is nil
        print(dict["spouse"] is NSNull, dict["phone"] == nil)
    }
} catch {
    print("not valid JSON:", error)
}

// When every value has the same type, JSONDecoder does it without Any
let scores = #"{"ada": 92, "linus": 78, "grace": 88}"#
let byName = try JSONDecoder().decode([String: Int].self,
                                      from: Data(scores.utf8))
for (name, score) in byName.sorted(by: { $0.key < $1.key }) {
    print(name, score)
}

Output

The sorted keys print as ["address", "age", "langs", "name", "spouse"]; print the dictionary itself and the order changes from run to run. Each cast pulls out a typed value, so age + 1 gives 37 and the nested object is one more [String: Any] cast. true true shows the difference between JSON null, which arrives as NSNull, and a key that isn't there at all, which reads as nil. The typed [String: Int] decode needs no casts. For anything you read more than once, a Decodable struct is safer: a typo in a key string or a wrong as? just gives nil here, with no error to tell you why.

7Which should you use?

MethodType safetyErrorsBest for
Decodable + JSONDecoderTypedDecodingError with key and pathAlmost all JSON with a known shape
CodingKeysTypedSame as aboveRenaming a few keys, skipping properties
.convertFromSnakeCaseTypedSame as aboveAPIs that use snake_case for every key
init(from:) + decodeIfPresentTypedSame as aboveDefaults for missing keys, fallback values
JSONSerializationAny, cast by handOnly for invalid JSON; bad casts give nilUnknown shapes, a value or two from a big payload

Frequently asked questions

How do I read a JSON file in Swift?

Load the bytes with try Data(contentsOf: url) and pass them to JSONDecoder().decode(MyType.self, from: data). For a file on disk, build the URL with URL(fileURLWithPath: "path/to/file.json"). For a file shipped in an app, use Bundle.main.url(forResource: "file", withExtension: "json"), which returns nil when the file is not part of the target. A missing file throws CocoaError.fileReadNoSuchFile, separate from any decoding error.

How do I convert a JSON string to a dictionary in Swift?

Use try JSONSerialization.jsonObject(with: Data(json.utf8)) as? [String: Any], then cast each value with as?, for example dict["age"] as? Int. If every value has the same type, try JSONDecoder().decode([String: Int].self, from: data) gives a typed dictionary with no casting. Either way, a dictionary has no fixed order, so sort its keys before printing it.

How do I make an enum Decodable in Swift?

Give it a String or Int raw type and add Decodable: enum Status: String, Decodable { case active, suspended }. The JSON value must match a raw value; set one with case pendingReview = "pending_review" when the names differ. An unknown value throws DecodingError.dataCorrupted ("Cannot initialize Status from invalid String value deleted"). To accept it instead, write init(from:) that decodes a String from singleValueContainer() and returns a fallback case when init(rawValue:) gives nil.

How do I exclude a property from Codable?

Declare a CodingKeys enum that lists only the properties you want coded, and give the excluded property a default value: var isSelected = false. It is then neither decoded nor encoded. Without the default, the build fails with "type 'User' does not conform to protocol 'Decodable'", because the decoder has no way to set it.

Can missing keys use a default value instead of an optional property?

Yes, but not with a default on the property alone: var fontSize = 14 still throws keyNotFound when the key is missing, because the synthesized decoder requires every key. Write init(from:) and use try container.decodeIfPresent(Int.self, forKey: .fontSize) ?? 14. That also maps a JSON null to the default, while a value of the wrong type still throws.

Why does JSONDecoder fail with "The given data was not valid JSON"?

The text is not JSON at all: a missing quote or bracket, single quotes, a trailing comma, or an HTML error page where you expected JSON. It is a DecodingError.dataCorrupted at the top level, before any key is checked. Print the first part of the string or file to see what you actually received.

Does JSONDecoder fail on extra keys in the JSON?

No. It reads only the keys your type declares and ignores the rest, so a server can add fields without breaking older clients. JSONDecoder has no option to reject unknown keys. The opposite case, a key your type needs that the JSON lacks, throws DecodingError.keyNotFound unless the property is optional or init(from:) supplies a default.

Run it yourself

Open any of these in the full Swift editor to tweak, run and share.

Swift playground