Skip to content
Tutorials Center
My learning

Topics

Lesson 98 of 146 ยท Standard Library and Foundation

Working with JSON

Encode and decode JSON in Swift with Codable, JSONEncoder and JSONDecoder - output formatting, key and date strategies, CodingKeys, DecodingError paths, JSONSerialization and a JSONValue enum.

JSON is the language of web APIs, configuration files and data exchange. A JSON document is built from only six kinds of value: objects, arrays, strings, numbers, true/false and null. Swift maps those to its own types, and the Codable system converts in both directions. You describe your data as ordinary structs, and the compiler writes the conversion code for you.

You met the basics in Codable. This lesson is the practical guide for JSON: formatting options, naming and date conventions, optional and missing fields, reading the error when JSON does not match your types, handling data whose shape you do not know in advance, and where JSONSerialization still fits. It uses Data and Bytes because JSON travels as UTF-8 bytes.

Encoding a struct

JSONEncoder.encode(_:) turns any Encodable value into Data. Wrap it in String(decoding:as:) to see the text. By default the output is compact, and, important for tests, the key order of objects is not stable, so ask for sorted keys whenever you compare or print JSON.

Swift Encoding with output options

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The compact form shows several defaults at once. The date is a number, -978220800, because the default Date encoding counts seconds from the 2001-01-01 reference date, not from 1970. The zip property is nil, and an optional that is nil is simply left out of the object (there is no "zip": null). The URL becomes a string, and by default its slashes are escaped as https:\/\/example.com\/ada, which is valid JSON but ugly. The second call adds .prettyPrinted (two-space indent, a space on both sides of the colon), .withoutEscapingSlashes, and the ISO 8601 date strategy, so joined reads 1970-01-02T00:00:00Z.

Always set a dateEncodingStrategy and a matching dateDecodingStrategy explicitly. .iso8601 is the most portable choice, and .secondsSince1970 fits systems that use Unix time. The default reference-date numbers will confuse every non-Swift consumer.

Decoding and naming strategies

Decoding reverses it with JSONDecoder.decode(_:from:). The decoder needs the type you expect, and it must be told about the same date convention. Many APIs also use snake_case keys while Swift properties use camelCase; instead of writing CodingKeys for every struct, set a key strategy once.

Swift Round trip with snake_case keys and dates

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The JSON uses check_in, guest_name and room_number, and the date is 2026-03-05T10:30:00Z. Decoding gives an equal struct. Remember that .iso8601 accepts only whole seconds; a string with milliseconds such as 10:30:00.123Z fails, and then you need a .custom strategy with your own formatter.

What each Swift type becomes

Knowing the mapping avoids surprises. The next program encodes many values and prints the JSON for each (sorted keys), including some that fail.

Swift How Swift values appear as JSON

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Line by line: an optional set to nil disappears ({"b":"x"}); plain dictionaries with string keys become objects; a bare string, a number and nil are valid JSON by themselves ("just a string", 42, null), which the modern parser accepts at the top level. Data becomes a Base64 string ("AQID"), Decimal a number (19.99), and a UUID its uppercase string. A String-backed enum encodes as its raw value, "red".

Two results need care. A dictionary whose keys are an enum (or any type other than String or Int) does not become an object; it becomes a flat array of alternating keys and values, ["red",1]. If you want an object, use String keys. And an enum with associated values becomes an object with the case name as the key, with the labels as inner keys: {"circle":{"radius":2}}, and a case without data is {"unit":{}}. If your API expects a different shape (such as {"type":"circle","radius":2}), write init(from:) and encode(to:) yourself.

The last two lines show that nan and infinity throw EncodingError.invalidValue, since JSON has no representation for them. Either avoid them or set nonConformingFloatEncodingStrategy.

CodingKeys, defaults and optional fields

When JSON names do not match your property names, or you need defaults for fields that are sometimes missing, write a CodingKeys enum and, if needed, your own init(from:). The synthesized decoder treats an Optional property as "may be missing", but a non-optional property with a default value is still required. A custom initializer fixes that.

Swift CodingKeys and default values

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The first product lacks in_stock and tags, so it gets the defaults true and []. The second keeps its values. Encoding writes the JSON names again: "in_stock", "name" and "price_cents". decodeIfPresent returns nil for a missing key (and for null), which ?? default turns into the default. A custom init(from:) is also the place to validate (reject a negative price) or to accept two spellings of the same field.

Unknown extra keys in the JSON are ignored by default, which is good for forward compatibility. Only the keys you ask for matter.

Reading decoding errors

Real JSON is rarely perfect. JSONDecoder throws a DecodingError, and each case tells you what went wrong and, in the context's codingPath, where in the document. Printing that path is the fastest way to debug a failing API response.

Swift The four kinds of DecodingError

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The results, in order: the good document prints ok: Item(id: 1, price: 2.5). A missing price is keyNotFound with an empty path (it is missing at the top level). A string where a number belongs is typeMismatch at ["id"] ("Expected to decode Int but found a string instead."). A null for a non-optional is valueNotFound. Truncated text and a fractional number for an Int both arrive as dataCorrupted ("The given data was not valid JSON."), the extra key is ignored (and 2 is happily read as the Double 2.0), and an array where an object is expected is a typeMismatch against Dictionary<String, Any>.

If you do not catch the error at all, the full message is printed with the path inside the document. Here a list of two items has a bad price in the second one:

Swift An uncaught decoding error (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The program stops, writes this to stderr, and ends with SIGILL:

TEXT
Swift/ErrorType.swift:254: Fatal error: Error raised at top level: DecodingError.typeMismatch: expected value of type Double. Path: [1].price. Debug description: Expected to decode Double but found a string instead.

[1].price says "the element at index 1, then its price key". In a real program, catch the error at the boundary where data enters, log that path and return a clear failure; never try! on data from outside.

Finally, a type that contains something that is not Codable cannot be synthesized, and the compiler tells you which property is to blame:

Swift A non-Codable property (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

TEXT
main.swift:5:8: error: type 'Config' does not conform to protocol 'Decodable'
note: cannot automatically synthesize 'Decodable' because 'Connection' does not conform to 'Decodable'

The same pair of messages appears for Encodable. Make Connection conform to Codable too, or exclude the property with CodingKeys.

Unknown or dynamic JSON: JSONSerialization

Sometimes you cannot write a struct: the shape varies, or you only need one field from a large response. JSONSerialization parses JSON into Foundation's untyped objects: [String: Any], [Any], String, numbers, Bool and NSNull. You then cast your way down.

Swift Untyped JSON with JSONSerialization

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Casting works as expected: Optional("Ada"), Optional(36) and Optional(3.14). JSON null appears as NSNull, not Swift nil, so check is NSNull. Writing is symmetric, and isValidJSONObject tells you in advance that a Date cannot be written (the real call would throw an Objective-C exception, which Swift cannot catch). Invalid text is an NSCocoaErrorDomain error with code 3840.

This approach is flexible but loses safety: every access is a cast, typos in keys are silent, and number bridging (as? Int versus as? Double) can differ between Apple platforms and Linux. Use it for exploration and small extractions, and use Codable for anything you rely on.

A typed tree for any JSON

You can have both flexibility and type safety by modeling JSON itself as an enum with associated values that conforms to Codable. Each case holds one JSON kind, and the decoder tries them in turn.

Swift A JSONValue enum that decodes any JSON

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The decoded tree prints as {"a": [1.0, 2.0, {"b": null}], "c": "x", "d": true, "e": 1.5}. All numbers become Double, so 1 prints as 1.0, and encoding writes it as 1 again; the round trip text is {"a":[1,2,{"b":null}],"c":"x","d":true,"e":1.5}. The last lines show how to dig into the tree with pattern matching. Order matters in the decoder: Bool is tried before Double, so true is not mistaken for a number. The JSON parser project builds such a tree by hand from raw text.

Practical advice

  • Match the contract, not your wishes. Model optional fields as Optional, give new fields defaults in init(from:), and ignore unknown keys.
  • Large integers: JSON numbers read by JavaScript lose precision above 2^53. Send 64-bit ids as strings if a browser consumes them.
  • Money: decode prices as integer cents or Decimal, never Double.
  • Do not decode on the main actor. Parsing megabytes of JSON blocks whatever thread does it; do it in a background Task.
  • Test with real samples. Keep a few real API responses as fixtures and decode them in tests.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A struct has var zip: String? and the value is nil. What does JSONEncoder produce for it by default?

    Synthesized encoding uses encodeIfPresent for optionals, so a nil value leaves the key out.
  2. 2. Why should you set outputFormatting = [.sortedKeys] in tests?

    Dictionaries have no stable order, so sorted keys make the text deterministic and comparable.
  3. 3. Which DecodingError case do you get when a required key is absent?

    keyNotFound carries the missing key and a context with the coding path.
  4. 4. How does JSON null appear when you read data with JSONSerialization?

    [String: Any] cannot hold nil, so the value is NSNull(); check with is NSNull.
  5. 5. What does [Color.red: 1] encode to when Color is a String-backed enum?

    Only String and Int keys produce a JSON object. Use String keys when you need an object.

Summary

  • JSONEncoder and JSONDecoder convert Codable types to and from UTF-8 Data; the compiler generates the code.
  • Set outputFormatting (.prettyPrinted, .sortedKeys, .withoutEscapingSlashes) and always choose explicit date strategies (.iso8601).
  • keyEncodingStrategy / keyDecodingStrategy handle snake_case; CodingKeys rename individual fields.
  • nil optionals are omitted; a custom init(from:) with decodeIfPresent supplies defaults. Unknown keys are ignored.
  • DecodingError has four cases and a codingPath that pinpoints the problem; catch it where data enters the program.
  • JSONSerialization gives untyped [String: Any] data with NSNull for null; a Codable JSONValue enum is the type-safe alternative for unknown shapes.

Next: Random Numbers shows how to generate random values and how to make them reproducible with a seeded generator.