0Pricing
Swift Academy · Lesson

Encoding with JSONEncoder

Produce JSON data from Swift values.

Encoding with JSONEncoder is a free Swift Academy lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Swift Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Creating a JSONEncoder

JSONEncoder is the workhorse that turns any Encodable value into JSON Data. Create one, then call encode(_:) on your value.

import Foundation

struct Movie: Codable {
    var title: String
    var year: Int
}

let encoder = JSONEncoder()
let data = try encoder.encode(Movie(title: "Up", year: 2009))
print(data.count, "bytes")

From Data to a Readable String

encode(_:) returns binary Data. To read it, decode the bytes as UTF-8 with String(data:encoding:).

import Foundation

struct Movie: Codable {
    var title: String
    var year: Int
}

let data = try JSONEncoder().encode(Movie(title: "Up", year: 2009))
let text = String(data: data, encoding: .utf8)!
print(text)

Pretty-Printed Output

By default JSON is compact. Set outputFormatting = .prettyPrinted to add indentation and newlines, making the result easy for humans to read.

import Foundation

struct Movie: Codable {
    var title: String
    var year: Int
}

let encoder = JSONEncoder()
encoder.outputFormatting = .prettyPrinted
let data = try encoder.encode(Movie(title: "Up", year: 2009))
print(String(data: data, encoding: .utf8)!)

Sorted Keys for Stable Output

Combine options with an array. Adding .sortedKeys orders keys alphabetically, which makes output deterministic — great for tests and snapshots.

import Foundation

struct Movie: Codable {
    var title: String
    var year: Int
    var rating: Double
}

let encoder = JSONEncoder()
encoder.outputFormatting = [.prettyPrinted, .sortedKeys]
let data = try encoder.encode(Movie(title: "Up", year: 2009, rating: 4.8))
print(String(data: data, encoding: .utf8)!)

Encoding Arrays

You can encode collections directly. An array of Encodable values becomes a JSON array.

import Foundation

struct Movie: Codable {
    var title: String
    var year: Int
}

let list = [Movie(title: "Up", year: 2009),
            Movie(title: "Coco", year: 2017)]
let data = try JSONEncoder().encode(list)
print(String(data: data, encoding: .utf8)!)

Encoding Dictionaries

A [String: Encodable-element] dictionary encodes to a JSON object. Note the key order is not guaranteed unless you add .sortedKeys.

import Foundation

let scores: [String: Int] = ["alice": 90, "bob": 75]
let encoder = JSONEncoder()
encoder.outputFormatting = .sortedKeys
let data = try encoder.encode(scores)
print(String(data: data, encoding: .utf8)!)

Encoding Nested Structures

Nested Codable types are encoded recursively, producing nested JSON objects automatically.

import Foundation

struct Author: Codable { var name: String }
struct Post: Codable {
    var title: String
    var author: Author
}

let p = Post(title: "Hello", author: Author(name: "Mae"))
let encoder = JSONEncoder()
encoder.outputFormatting = .prettyPrinted
print(String(data: try encoder.encode(p), encoding: .utf8)!)

Reusing an Encoder

A configured JSONEncoder can be reused for many values. Configure it once and keep applying the same formatting throughout your code.

import Foundation

struct Tag: Codable { var name: String }

let encoder = JSONEncoder()
encoder.outputFormatting = .sortedKeys
for t in [Tag(name: "swift"), Tag(name: "json")] {
    let data = try encoder.encode(t)
    print(String(data: data, encoding: .utf8)!)
}

Encoding Numbers and Booleans

Numeric and boolean properties encode as JSON literals — no quotes. Strings are quoted; Int, Double, and Bool are not.

import Foundation

struct Stats: Codable {
    var count: Int
    var ratio: Double
    var enabled: Bool
}

let data = try JSONEncoder().encode(Stats(count: 3, ratio: 0.75, enabled: true))
print(String(data: data, encoding: .utf8)!)

Encoding Optionals

By default a nil optional is omitted from the JSON entirely. A non-nil optional encodes as its wrapped value.

import Foundation

struct Item: Codable {
    var name: String
    var note: String?
}

let data = try JSONEncoder().encode(Item(name: "Pen", note: nil))
print(String(data: data, encoding: .utf8)!)

Putting It Together

A typical encode flow: build the value, configure the encoder, call encode, then convert Data to a String for logging or transport.

import Foundation

struct Order: Codable {
    var id: Int
    var items: [String]
}

let order = Order(id: 42, items: ["a", "b"])
let encoder = JSONEncoder()
encoder.outputFormatting = [.prettyPrinted, .sortedKeys]
let data = try encoder.encode(order)
print(String(data: data, encoding: .utf8)!)

Quick Check: JSONEncoder

Test your encoding knowledge.

Recap: Encoding with JSONEncoder

You learned to turn Swift values into JSON:

  • encode(_:) returns Data; convert with String(data:encoding:).
  • outputFormatting with .prettyPrinted and .sortedKeys controls layout.
  • Arrays, dictionaries, nested types, numbers, booleans, and optionals all encode sensibly.
  • A configured encoder can be reused across many values.

Frequently asked questions

Is the “Encoding with JSONEncoder” lesson free?

Yes — the full text of “Encoding with JSONEncoder” is free to read here on the web, and the Swift Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Swift Academy course, upgrade to CoddyKit PRO.

What will I learn in “Encoding with JSONEncoder”?

Produce JSON data from Swift values. You practise Swift Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Swift Academy?

No prior experience is required. Swift Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Encoding with JSONEncoder” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Swift Academy lesson?

Yes. Every Swift Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Conforming to Codable
  2. Encoding with JSONEncoder
  3. Decoding with JSONDecoder
  4. Handling Optional and Nested Types
← Back to Swift Academy