PureYAMLJSON is a separate library product layered on the core engine. JSON is a subset of YAML 1.2, so the existing parser already reads both into one value tree; this product adds the missing half and the value-level policy: - JSON.Writer: a pure-Swift RFC-8259 serializer (no Foundation; WASI-clean), pretty or compact, rejecting non-string keys and non-finite numbers. - JSON representability rules expressed in PureYAML's own Validation framework: mappingKeysAreStrings and numbersAreFinite join the core mappingKeysAreUnique. - JSON.Validator: the representability rule set plus issues(for:)/isRepresentable. - JSON.Convert: standalone convert(_:to:) with the round-trip law (parse -> validate representability -> emit -> re-parse must equal the source). To JSON rejects complex keys and non-finite numbers; to YAML rejects duplicate keys, which are legal in JSON but not in YAML. 19 tests cover the writer, the rules, and both conversion directions including the dual-rejection edges. Carved out of the catch-all Sources/Tests paths via exclude so the core PureYAML target is unchanged.
36 lines
1.6 KiB
Swift
36 lines
1.6 KiB
Swift
import PureYAML
|
|
|
|
public extension PureYAML.JSON {
|
|
/// JSON-representability checks built on PureYAML's own validation framework.
|
|
/// The parser already guarantees the input is well-formed YAML (and so covers
|
|
/// JSON syntax); this layer reports the value-level reasons a tree cannot be
|
|
/// emitted as JSON: a non-string mapping key, a non-finite number, or (for a
|
|
/// deterministic single-meaning document) a duplicate key.
|
|
///
|
|
/// JSON the format tolerates duplicate object names, but a tree that carries two
|
|
/// pairs with the same key emits an ambiguous document, so the representability
|
|
/// validator rejects duplicates for determinism. Drop ``unique`` from the rule
|
|
/// set if you want the permissive reading.
|
|
enum Validator {
|
|
/// The full JSON-representability rule set: unique keys, string keys, finite
|
|
/// numbers. Suitable to pass straight to `PureYAML.JSON.Convert`.
|
|
public static var representability: PureYAML.Validation.Validator {
|
|
PureYAML.Validation.Validator(rules: [
|
|
.mappingKeysAreUnique,
|
|
.mappingKeysAreStrings,
|
|
.numbersAreFinite,
|
|
])
|
|
}
|
|
|
|
/// Every reason the value cannot be emitted as strict JSON, in document order.
|
|
public static func issues(for value: PureYAML.Model.Value) -> [PureYAML.Validation.Issue] {
|
|
representability.collect(value).issues
|
|
}
|
|
|
|
/// Whether the value can be emitted as strict JSON.
|
|
public static func isRepresentable(_ value: PureYAML.Model.Value) -> Bool {
|
|
issues(for: value).isEmpty
|
|
}
|
|
}
|
|
}
|