JSON.parse source text access
Background
JSON.parse is lossy, even with a reviver function
// Numbers are subject to IEEE 754 precision limits.�JSON.parse(" 9999999999999999")�// → 10000000000000000��// …and reviver functions receive already-parsed values.�JSON.parse(" 9999999999999999", (key, val) => BigInt(val))�// → 10000000000000000n
Reviver functions lack context
// Conditional processing must bubble up to a differentiating level�JSON.parse(`{ "metadata": { "date": "2018-09-25T10:00-04:00" },� "value": { "date": "2018-09-25T10:00-04:00" } }`,� function(key, val) {� if ( key === "value" && "date" in val ) {� val.date = new Date(val.date);� }� return val;� }�)
// → { metadata: { date: "2018-09-25T10:00-04:00" },� value: { date: new Date("2018-09-25T14:00:00.000Z") } }
Proposal
Expose source text to reviver functions
// Numbers are still subject to IEEE 754 precision limits.�JSON.parse(" 9999999999999999")�// → 10000000000000000��// …but reviver functions gain access to the raw source.�JSON.parse(" 9999999999999999", (key, val, {source}) => BigInt(source))�// → 9999999999999999n
Potential enhancement: Supply parent keys
// Conditional processing can take place directly at a deep value.�JSON.parse(`{ "metadata": { "date": "2018-09-25T10:00-04:00" },� "value": { "date": "2018-09-25T10:00-04:00" } }`,� (key, val, {keys}) =>� keys.length === 3 && keys.join(".") === ".value.date" ?� new Date(val) :� val�)
// → { metadata: { date: "2018-09-25T10:00-04:00" },� value: { date: new Date("2018-09-25T14:00:00.000Z") } }
Discussion
Draft spec text
1.1 Runtime Semantics: InternalizeJSONProperty ( holder, name, reviver, parseNode )
The abstract operation InternalizeJSONProperty is a recursive abstract operation that takes twofour parameters: a holder object and, the String name of a property in that object, a reviver function, and a parseNode Parse Node corresponding with the original value of the property. InternalizeJSONProperty uses the value of reviver that was originally passed to the above parse function.
Draft spec text
Draft spec text
Draft spec text
Other questions
Other questions
Next steps
Questions?
Feedback?
Advance to Stage 2?
What is Stage 2?
| Stage | Purpose | Entrance Criteria | Acceptance Signifies | Spec Quality | Post-Acceptance Changes Expected | Implementation Types Expected* |
2 | Draft | Precisely describe the syntax and semantics using formal spec language | Initial spec text | The committee expects the feature to be developed and eventually included in the standard | Draft: all major semantics, syntax and API are covered, but TODOs, placeholders and editorial issues are expected | Incremental | Experimental |