tc39 / proposal-json-parse-with-source

Proposal for extending JSON.parse to expose input source text.
https://tc39.github.io/proposal-json-parse-with-source
MIT License
214 stars 9 forks source link

Supply an array of keys for understanding value context? #11

Open gibson042 opened 4 years ago

gibson042 commented 4 years ago

A reviver function sees values bottom-up, but the data structure hierarchy is already known and can be supplied to it, with or without the phantom leading empty string.

const input = '{ "foo": [{ "bar": "baz" }] }';
const expectedKeys = ['foo', 0, 'bar'];
let spiedKeys;
JSON.parse(input, (key, val, {keys}) => (spiedKeys = spiedKeys || keys, val));
expectedKeys.length === spiedKeys.length;
// → true
expectedKeys.every((key, i) => spiedKeys[i] === key);
// → true

This kind of context can be important for location-dependent reviving (e.g., convert a member like "timeCreated": "2020-02-06T02:24Z" to a Date instance when it appears in the representation of a REST resource, but not when it appears in the representation of a collection of freeform key–value tags.

gibson042 commented 4 years ago

There was consensus on the TC39 Incubator call to not provide keys in this proposal unless a significant use case is identified. This functionality is potentially valuable for practitioners, but can be easily added to the proposal or a followup.

In order to inform decisions around such an addition and address concerns about memory pressure, implementations should collect statistics about use of JSON.parse with large input and a reviver function. Parallels were also drawn to the currently-Stage-3 RegExp Match Indices proposal.

haoadoreorange commented 2 years ago

We're having a defined use case for this. Which is "sorta" implemented here: https://github.com/haoadoresorange/when-json-met-bigint

The roundtrip example in the README of this proposal will fail if the number is within the range for number type. In the repo above we allow the use of a "schema" to enforce such roundtrip.

jandem commented 1 year ago

As an implementer, I'm a bit concerned about adding more overhead (performance, complexity) for this relatively niche use case.

Maybe this could be a follow-up proposal, since it's strictly an addition (adding another property to the context object)?