Complete Guide for
in Swift and Objective-C
Foundation has read JSON5 since iOS 15 and macOS 12. The useful part is exactly what it accepts.
Apple decodes JSON5 through JSONDecoder.allowsJSON5 and JSONSerialization. Both are off by default, neither writes JSON5, and the second option does not exist in the open-source Foundation used on Linux.
We read the parser's source and compared it with the grammar. It rejects \0, \v and raw tabs, keeps the first of two duplicate keys and turns a backslash-newline into a newline. Below you will find the OS versions, working Codable patterns, error handling and the full list of differences.
TL;DR: Set decoder.allowsJSON5 = true on iOS 15, macOS 12, tvOS 15, watchOS 8 or visionOS 1 and later, or pass .json5Allowed to JSONSerialization. Reading is built in; writing is not, because both encoders emit strict JSON. On older systems or when you need exact spec behavior, use a package. Our findings come from reading Apple's open-source scanner (swift-foundation 6.4.3), not from running a device, so test on your deployment target.
What Apple Provides and Where
Foundation has two entry points, one for Codable and one for the older object-graph API. All four switches below share the same availability, according to Apple's documentation pages for each: iOS 15.0, iPadOS 15.0, Mac Catalyst 15.0, macOS 12.0, tvOS 15.0, visionOS 1.0 and watchOS 8.0.
| Switch | Swift | Objective-C | Purpose |
|---|---|---|---|
JSONDecoder.allowsJSON5 | var allowsJSON5: Bool | Not applicable | Decoding accepts the JSON5 syntax |
JSONDecoder.assumesTopLevelDictionary | var assumesTopLevelDictionary: Bool | Not applicable | The top level is a dictionary even without braces |
JSONSerialization.ReadingOptions.json5Allowed | static var json5Allowed | NSJSONReadingJSON5Allowed | Reading accepts the JSON5 syntax |
JSONSerialization.ReadingOptions.topLevelDictionaryAssumed | static var topLevelDictionaryAssumed | NSJSONReadingTopLevelDictionaryAssumed | The top level is a dictionary even without braces |
Apple calls the brace-less option "an extension to JSON5 that's not part of the specification" and says AttributedString uses it for Markdown such as ^[custom attribute](factor: 10, other: true), where the part in parentheses is JSON5 without braces. Apple's description of the format lists single- and double-quoted strings, multi-line strings, comments, hexadecimal numbers, leading and trailing decimal points, an explicit plus sign, Infinity and NaN. It does not mention unquoted keys or trailing commas, but the source we read handles both.
Linux and other non-Apple toolchains. The decoder lives in the open-source swift-foundation package, in FoundationEssentials, and its allowsJSON5 declaration carries the same availability annotation for Apple systems (macOS 12.0, iOS 15.0, tvOS 15.0, watchOS 8.0); we did not run it on Linux. The older class is different: in swift-corelibs-foundation, JSONSerialization.ReadingOptions contains only mutableContainers, mutableLeaves, fragmentsAllowed and a deprecated allowFragments. There is no json5Allowed, and a comment in the repository's own plutil tool says "JSON5 is unimplemented in swift-corelibs-foundation's JSONSerialization". Code shared with Linux should therefore use JSONDecoder.
Decoding with Codable
Turn the flag on before decoding, then use Codable types as usual. The key and date strategies, userInfo and every other option still apply. We could not compile Swift in this environment, so the samples below are not run; the expected values come from Foundation's own tests and source, which check hex integers such as 0x1F and -0X1f and leading or trailing decimal points like .5 and 1..
import Foundation
struct ServerConfig: Codable {
var name: String
var port: Int
var timeout: Double
var upstreams: [Upstream]
struct Upstream: Codable {
var host: String
var weight: Int
}
}
let text = """
{
// edge proxy settings
name: 'edge-proxy',
port: 0x1F90,
timeout: .75,
upstreams: [
{ host: "10.0.0.5", weight: 2 },
{ host: "10.0.0.6", weight: 1 },
],
}
"""
let decoder = JSONDecoder()
decoder.allowsJSON5 = true
let config = try decoder.decode(ServerConfig.self, from: Data(text.utf8))
print(config.port) // 8080Brace-less documents
Setting assumesTopLevelDictionary lets a file or string omit the outer braces. Foundation's tests expect the input below to decode to a two-entry dictionary, expect a trailing comma and trailing whitespace to be fine, expect empty input to produce an empty dictionary, and expect a lone closing or opening brace to fail. A document that does start with { must also end with }.
let decoder = JSONDecoder()
decoder.allowsJSON5 = true
decoder.assumesTopLevelDictionary = true
let input = #"hello: "world", goodbye: "42""#
let settings = try decoder.decode([String: String].self, from: Data(input.utf8))
// ["hello": "world", "goodbye": "42"] The option works with or without allowsJSON5, according to Apple's property comment in the source ("Compatible with both JSON5 and non-JSON5 mode"). With the JSON5 switch off, the brace-less form (and the forgiven trailing commas described next) is the only relaxation you get.
Plain JSONDecoder already forgives trailing commas. Foundation's scanners for both modes carry the comment "the foundation json implementation does support trailing commas", and its tests expect trailing commas in arrays and objects to decode with allowsJSON5 left off. Do not rely on a strict-JSON decoder to reject them.
Error Handling
A syntax error surfaces as DecodingError.dataCorrupted whose debugDescription is always the same sentence, "The given data was not valid JSON." The useful detail sits in underlyingError. According to the source, that value is an NSError in the Cocoa error domain with the code for a corrupt property list, and its NSDebugDescriptionErrorKey carries text of the form "Invalid escape sequence 'q' around line L, column C." (the numbers vary). On non-Apple builds underlyingError is nil, so there you get no position at all. Type problems after a successful parse use the normal Codable errors, typeMismatch and keyNotFound.
do {
let config = try decoder.decode(ServerConfig.self, from: data)
print(config.name)
} catch DecodingError.dataCorrupted(let context) {
print(context.debugDescription) // The given data was not valid JSON.
if let underlying = context.underlyingError as NSError? {
// Apple platforms: the line and column text is here.
print(underlying.userInfo[NSDebugDescriptionErrorKey] ?? "")
}
} catch {
print(error) // typeMismatch, keyNotFound, ...
} Two behaviors to plan for. The scanner finds the structure of the document first and, by its own source comments, leaves strings and numbers "not completely parsed until decoding time", so a malformed value inside a field your type never reads may go unreported (an inference from that comment; we did not run it). And a decimal number that overflows, such as 1e400, throws "not representable in Swift" when decoded into a Double, where the reference JavaScript package returns Infinity. The spec lets parsers limit number range, so this is allowed, but the literal Infinity is the only way to get an infinite value.
Where Foundation Differs from the Specification
The JSON5 specification requires a parser to "accept all texts that conform to the JSON5 grammar". We checked Apple's scanner against it by reading JSON5Scanner.swift and the decoder in the swift-foundation tag swift-6.4.3-RELEASE (published November 20, 2026), plus the project's tests. The main branch has the same logic in a rewritten file. Apple's own operating systems ship Foundation as a binary, so an older OS may behave differently; a comment in the tests says an earlier NSJSONSerialization accepted a symbol as an unquoted key that the new implementation rejects. Treat the table as a map of what to test, not a guarantee for every device.
| Topic | Specification | Foundation (source of 6.4.3) |
|---|---|---|
| Backslash before a newline in a string | The backslash and line terminator add nothing to the value | Adds a newline: 'a\ then a line break then b' decodes to "a", a newline, "b" (CR and CRLF are kept as written) |
\0 and \v | Valid escapes | Rejected as an invalid escape; Foundation's tests expect "hi\0there" to fail |
\x00 and \u0000 | Valid | Rejected ("Unsupported escaped null") |
Other escaped letters such as \a or \q | The letter, without the backslash (digits 1 to 9 excepted) | Rejected ("Invalid escape sequence") |
| Raw control characters in a string, including a tab | Allowed by ECMAScript 5 for every character except line terminators | Rejected ("Unescaped control character") |
| Accepted escapes | Single-character escapes, \u and \x | \" \' \\ \/ \b \f \n \r \t, \uXXXX and \xXX |
| Whitespace between tokens | Tab, line feed, vertical tab, form feed, carriage return, space, U+00A0, U+2028, U+2029, U+FEFF and any other Zs character | The first six are skipped. The code compares single bytes, with 0xA0 for the no-break space, so the multi-byte UTF-8 forms of U+00A0, U+2028, U+2029 and U+FEFF are not skipped between tokens. A byte order mark at the start of the data is removed separately. |
End of a // comment | Any line terminator, including U+2028 and U+2029 | Only a line feed or a carriage return |
| Unquoted keys | ECMAScript 5.1 IdentifierName, \u escapes allowed | Letters, $ and _ to start, then marks, digits and connectors; \u and also \x escapes inside the key |
| Hexadecimal numbers | Any number of digits | Read as a 64-bit integer; into Float or Double only if exactly representable (tests expect a 22-digit hex literal, 0xFFFFFFFFFFFFFFFFFFFFFF, to fail as a Double; the decoder tries Int64, then UInt64, and keeps the result only if the floating-point type represents it exactly) |
Infinity and NaN | Exact case, optional sign | Exact case, optional sign |
| Duplicate keys | Not defined; the reference package keeps the last | Keeps the first value (also after a key-conversion strategy) |
| Nesting depth | Parsers may set limits | 512 levels, then "Too many nested arrays or dictionaries" |
| Input encoding | Text | UTF-8, UTF-16 or UTF-32, with or without a byte order mark, detected from the first bytes |
Practical consequences. A config author who writes \0, a literal tab in a string, or \v will get an error on Apple platforms and success in the reference parser. A multi-line string built with backslash-newline will contain real newlines, so the same file yields different strings in Swift and in JavaScript. If a file might hold the same key twice, the first entry wins in Swift and the last in JavaScript. The behavior is stable and testable, which is the point of the table: write a handful of fixture files and decode them in your own CI on the OS versions you ship, with the official corpus as a source of cases.
Scope of this reading. It covers JSON5Scanner.swift, the scanner the 6.4.3 decoder uses. The 6.5 development branch adds a second scanning path (JSONScannerEventSource) that its decoder selects on non-Apple builds, and Apple's feature flag may select it on newer Apple systems. We did not compare it line by line, so re-test after a toolchain upgrade.
Objective-C and JSONSerialization
NSJSONSerialization returns an object graph of dictionaries, arrays, strings and numbers, so it suits Objective-C code and loosely typed Swift. Pass the JSON5 option and, if you want brace-less input, the top-level option. On Apple platforms this class is closed source, so unlike the decoder we cannot read its scanner; do not assume it matches the table above.
NSData *data = [@"{ name: 'edge-proxy', port: 0x1F90, /* c */ }"
dataUsingEncoding:NSUTF8StringEncoding];
NSError *error = nil;
id config = [NSJSONSerialization JSONObjectWithData:data
options:NSJSONReadingJSON5Allowed
error:&error];
if (!config) {
NSLog(@"Invalid JSON5: %@", error);
return;
}let object = try JSONSerialization.jsonObject(
with: data,
options: [.json5Allowed, .topLevelDictionaryAssumed]
) The options type is old: ReadingOptions is listed from iOS 5.0 and macOS 10.7, and fragmentsAllowed controls whether a top-level number or string is accepted. The two JSON5 options are the new members. As an alternative to Foundation for Objective-C, ObjFW parses JSON5 in objectByParsingJSON, per its header documentation, with a default depth limit of 128.
Writing JSON5
Foundation has no JSON5 writer. JSONSerialization.WritingOptions offers four options, fragmentsAllowed, prettyPrinted, sortedKeys and withoutEscapingSlashes, and JSONEncoder writes the same strict JSON. That output is also valid JSON5, which is enough for most uses. What you cannot produce is anything beyond JSON: no comments, no unquoted keys, no trailing commas, and no bare Infinity or NaN. The encoder's nonConformingFloatEncodingStrategy either throws (the default) or converts those values to strings you choose, which readers then see as strings rather than numbers.
Packages fill part of the gap. swift-yyjson writes JSON and can emit Infinity and NaN literals with its .allowInfAndNaN write option. ObjFW is the only option we found that generates the syntax on purpose: its OFJSONRepresentationOptionJSON5 is documented as "Generate JSON5", and its source leaves identifier-shaped keys unquoted and writes NUL as \0 when no digit follows. If your product must write comments back into a user's file, none of these writers has a way to emit them; look at the round-trip libraries on the implementations page, or call one from Swift through a C interface.
Third-Party Packages
Reach for a package when you target systems older than iOS 15 or macOS 12, need identical behavior on every platform, or want a faster parser. We checked the repositories on November 29, 2026 but did not build or run them.
| Package | Version and date | License | Platforms | What it offers |
|---|---|---|---|---|
| mattt/swift-yyjson | 0.6.1, 2026-11-25 | MIT | Swift 6.1 or later; macOS 10.15, iOS 13, tvOS 13, watchOS 6, visionOS 1 | Drop-in YYJSONDecoder and YYJSONSerialization built on the C library yyjson. decoder.allowsJSON5 = true enables all JSON5 features, or you can enable them one by one; .json5Allowed exists for the serialization API. Its README says JSON5 support is unavailable when the strictStandardJSON package trait is enabled. |
| NSSimpleApps/NSKJSON | Tag 1.5; last push 2025-07-18 | MIT | Not checked | A Swift parser. NSKJSON.jsonObject(with: data, version: .json5) and a string variant; the README points to the official test suite and describes parsing only. |
| ObjFW | 1.5.7 | LGPL-3.0 (GitHub metadata) | Not checked | Parses JSON5 with objectByParsingJSON and generates it with OFJSONRepresentationOptionJSON5. It is a separate Objective-C framework with its own classes (OFString and so on), not an extension of Foundation. |
swift-yyjson inherits the behavior of the underlying C parser, including the deviations we measured on the C and C++ guide, such as a raw tab in a string in yyjson 0.13.0; we did not check which yyjson version the package bundles. Since both Apple's decoder and the packages are partial in different ways, the safest cross-platform habit is to avoid the corner cases in the table above: escape tabs, avoid \0, \v and line continuations in strings, and keep keys unique.
import YYJSON
let decoder = YYJSONDecoder()
decoder.allowsJSON5 = true
let config = try decoder.decode(ServerConfig.self, from: Data(text.utf8)) That snippet follows the package's README and assumes the ServerConfig type from earlier; we did not compile it.
JSON5 in Swift: Common Questions
Which OS versions can decode JSON5?
iOS 15, iPadOS 15, Mac Catalyst 15, macOS 12, tvOS 15, watchOS 8 and visionOS 1 and later, according to Apple's documentation. Older systems need a package such as swift-yyjson, which lists iOS 13 and macOS 10.15 as its floor.
Does it work on Linux?
JSONDecoder.allowsJSON5 is part of the open-source decoder, but we did not run it there. JSONSerialization on Linux has no JSON5 option at all.
Can Foundation write JSON5 with comments?
No. Both encoders emit strict JSON, which is valid JSON5 but has no comments. Foundation also cannot write Infinity or NaN as bare literals.
Why does my multi-line string contain newlines?
In the source we read, a backslash-newline inside a string adds a newline to the value, whereas the specification says the pair adds nothing. See the differences table.
How do I report where a syntax error is?
Read underlyingError inside DecodingError.dataCorrupted and print its debug description. It carries line and column on Apple platforms and is nil on non-Apple builds. For a pre-check in CI, validate the file with the command-line tool first.
Is it safe to decode untrusted JSON5?
The scanner caps nesting at 512 levels, which protects the stack, and we found no limit on input size in it. Cap the size yourself, and see the security tutorial for the wider checklist.
Sources
(11)
- Apple: JSONDecoder.allowsJSON5
- Apple: JSONDecoder.assumesTopLevelDictionary
- Apple: JSONSerialization.ReadingOptions.json5Allowed, topLevelDictionaryAssumed and the ReadingOptions overview
- Apple: JSONSerialization.WritingOptions and JSONEncoder.NonConformingFloatEncodingStrategy
- swift-foundation 6.4.3: JSON5Scanner.swift, JSONDecoder.swift and JSONScanner.swift
- swift-foundation 6.4.3 tests: JSONEncoderTests.swift
- swift-corelibs-foundation (
JSONSerialization.swiftandplutilon the main branch, November 25, 2026) - The JSON5 specification and json5-tests
- mattt/swift-yyjson README and Package.swift
- NSSimpleApps/NSKJSON README
- ObjFW (
OFString+JSONParsing.h,OFJSONRepresentation.handOFString.m)
Last reviewed: November 29, 2026.
JavaScript
Python
TypeScript
Node.js
Rust
Java
C#
Ruby
Kotlin
Lua
Babel
Vite
webpack
ESLint
Prettier
VS Code
JetBrains