JSON Schema allOf & JSON Parser duplicate‑key handling: interoperability concern
0 reputation · 20 Jun 2024, 16:34 UTC
0 reputation · 20 Jun 2024, 16:34 UTC
JSON Schema’s allOf keyword allows a schema to combine constraints from several subschemas. However, the JSON specification does not define how duplicate keys in an object should be treated. Most parsers silently accept the last occurrence, but some libraries preserve the first or raise an error. When a document containing duplicate keys is validated against an allOf schema, it is unclear which key value should be used by the validator, especially if the duplicate keys belong to different subschemas. This ambiguity can lead to subtle bugs when systems assume different semantics, making the interaction between allOf and duplicate‑key handling an unresolved decision that affects both validators and consumers.
What value should a validator consider when duplicate keys appear in a document validated against an allOf schema?
Should allOf subschemas enforce unique property names to avoid duplicate key conflicts?
How can libraries expose the duplicate key resolution strategy to consumers to ensure consistent interpretation?
31775 reputation · 21 Jun 2024, 03:15 UTC
When a JSON document contains duplicate keys, the value that a validator sees is whatever the JSON parser returns. Validators do not perform duplicate‑key resolution themselves; they operate on the parsed object. Therefore, the key value used by an allOf subschema is determined by the parser’s policy (first‑wins, last‑wins, or error).
If two subschemas in an allOf reference the same property name, the subschemas may expect different values. Depending on the parser’s policy, one subschema may pass while the other fails, or both may fail if the parser throws an error.
const obj = JSON.parse('{"a":1,"a":2}');
console.log(obj.a); // 1 or 2 depending on policy
uniqueItems on arrays or uniqueProperties (when available) to forbid duplicate property names.duplicateKeyPolicy: 'first' | 'last' | 'error' in the validator API.Run the same document through the validator with each policy if your library supports it, and verify that all subschemas in allOf behave as expected.
To tailor the recommendation for your environment, we need to know the parser’s duplicate‑key policy:
Validators rely on the parser’s outcome; therefore, the duplicate‑key policy must be understood, documented, and, if possible, configurable. Schemas should avoid ambiguous property names, and libraries should expose the policy to consumers to prevent subtle bugs when allOf subschemas reference the same key.
Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.