How to Parse JSON in Swift

← All guides

Swift uses the Codable protocol with JSONDecoder and JSONEncoder from Foundation. Conform your struct to Codable and decode from Data.

Decode into a Codable struct

Conform to Codable and decode the JSON Data into your type.

swift
struct User: Codable {
    let name: String
    let roles: [String]
}

let data = Data(text.utf8)
let user = try JSONDecoder().decode(User.self, from: data)
print(user.name)

Map snake_case keys

Set keyDecodingStrategy to convert snake_case JSON keys to camelCase properties automatically.

swift
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
let user = try decoder.decode(User.self, from: data)

Encode and pretty-print

JSONEncoder serializes; set outputFormatting for pretty output.

swift
let encoder = JSONEncoder()
encoder.outputFormatting = [.prettyPrinted, .sortedKeys]
let out = try encoder.encode(user)
print(String(data: out, encoding: .utf8)!)

Frequently Asked Questions

Codable is a type alias for Decodable & Encodable. Conforming a type to it lets JSONDecoder and JSONEncoder convert between JSON and your Swift types automatically.

Use the JSON to Swift tool to generate Codable structs with CodingKeys from a sample JSON document.

Add a CodingKeys enum to the struct to map JSON keys to property names, or use a key decoding strategy.

Related Tools