JSON
A JSON variant value. This value may contain a fragment, an array, or an object.
enum JSON
Overview
You can parse JSON from any Collection
of UTF-8 data using the init(parsing:)
initializer. For example, you can parse from a (sub)string via its UTF8View
.
let json:JSON = try .init(parsing: "{\"hello\": \"world\"}".utf8)
All instances of this type, including number(_:)
instances, can be round-tripped losslessly, as long as the initial encoding is performed by swift-json
.
As of version 0.3.0, re-encoding a swift-json
-encoded message is guaranteed to produce bytewise-identical output.
When re-encoding arbitrary JSON, the implementation makes a reasonable effort to preserve features of the original input. It will not re-order object fields, strip explicit null
values, or convert decimals to floating point. The parser does not preserve structural whitespace.
The implementation guarantees canonical equivalence when re-encoding values, but it may not preserve the exact expressions used to represent them. For example, it will normalize the escape sequences in "6\\/14\\/1946"
to "6/14/1946"
, because the escaped forward-slashes (/
) are non-canonical.
Decoding with Codable
JSON
implements Decoder
, so you can use it with any type that conforms to Decodable
.
Decoding with high-performance APIs
The standard library’s decoding system suffers from inherent inefficiencies due to how it is defined. The recommended way to decode JSON is to use its LintingDictionary
API, alongside this module’s Array
extensions.
Most of swift-json
’s linting and array APIs take closure arguments. You should perform decoding subtasks inside the closure bodies in order to take full advantage of the library’s error reporting.
These APIs are low-cost abstractions that only incur overhead when decoding fails. They can be significantly faster than the standard library’s Decoder
hooks, and only slightly more verbose than an equivalent Decodable
implementation.