Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
gibson042 opened this issue Feb 6, 2020 · 3 comments
Open

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

gibson042 opened this issue Feb 6, 2020 · 3 comments

Comments

@gibson042
Copy link
Collaborator

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
Copy link
Collaborator Author

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
Copy link

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
Copy link

jandem commented Jan 24, 2023

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)?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants