JSON to Swift Codable

Paste JSON and get Swift Codable structs for it below, as you type, ready for JSONDecoder.

CodingKeys only when needed

Properties are in camelCase. When a key is written otherwise (first_name, 2fa), the struct gets CodingKeys mapping each property to its key; when they all match, there are none. A key that is a Swift keyword is written in backquotes.

Optionals and numbers

A value that is null somewhere, or a key some items lack, is optional (String?), which Codable reads as nil when it is missing. Whole numbers are Int (Decimal past 64 bits) and decimals Double.

Values of any kind

Codable reads no Any, so values of mixed kinds are JSONValue, a small enum written at the end that reads and writes any JSON.

Types from sample data

Every item of a list, and every value of JSON Lines, is a sample of the same type: a key that some lack is optional, a value that is sometimes null is nullable, whole numbers mixed with decimals are decimals, and objects with the same keys share one type, named after the key they are under ("line_items" holds LineItem). An object whose keys are ids or dates, such as {"1001": {…}, "1002": {…}}, is a map. YAML, TOML, CSV and the other formats work too: pick their language above the editor.

Or the data as a dictionary

Data writes the JSON as a [String: Any] literal, the lists and dictionaries inside it marked [Any] and [String: Any] as Swift needs, and NSNull() for null.

Copy, download or switch

The Swift follows your typing, and a mistake in the JSON is pointed out first, with its line and column. Copy or Download (a .swift file) take it as it is. Above the code, switch between Types and Data, or pick another language; the Convert menu's Code item opens the one you picked last.

Private: nothing is uploaded

Formatting, checking and comparing all happen in your browser. Your documents are saved in the browser's own storage on this computer, not on a server, so they never leave your device.

With your permission, we count anonymous visits (which pages and tools are used), never what you type. See Privacy.

Questions

How do I decode the JSON?

try JSONDecoder().decode(Root.self, from: data). For snake_case keys you can instead set keyDecodingStrategy = .convertFromSnakeCase and leave the CodingKeys out.

Is my data uploaded anywhere?

Your documents aren't: everything runs in your browser, and they are saved on your computer, in the browser's storage for this site. With your permission we count anonymous visits, never their content.

More tools