this post was submitted on 24 Jun 2024
40 points (100.0% liked)

JavaScript

1826 readers
1 users here now

founded 1 year ago
MODERATORS
top 3 comments
sorted by: hot top controversial new old
[–] kinttach@lemm.ee 4 points 3 weeks ago (1 children)

Set and Map would be more useful if they were compatible with JSON. I see a lot of people using an object as a dictionary or an array as a set because of that.

[–] Kissaki@programming.dev 3 points 3 weeks ago* (last edited 3 weeks ago) (1 children)

Where would/should the mapping happen? Probably not the Set constructor. JSON.parseSet()?

JSON.parseSet = json => new Set(JSON.parse(json));
JSON.parseSet('["A", "B", "C", "A", "B"]'); // Set(3) [ "A", "B", "C" ]

/edit: JSON.parseMap()

JSON.parseMap = json => new Map(Object.entries(JSON.parse(json)));
JSON.parseMap('{"a":1,"b": 2}'); // Map { a → 1, b → 2 }
[–] kinttach@lemm.ee 2 points 3 weeks ago

There also needs to be some way to indicate that a JSON construct is a Set, Map, plain object, or array. You’d want a date/time type as well.

Without breaking existing JSON parsers, the way to do that is to add metadata like a _type field to an object, or to add a “sidecar” object like superjson does. Which works but is ugly IMO.

Then there’s BSON, YAML, JSON Schema, and the one we don’t mention ₓₘₗ. To my knowledge all of those could be extended in a way to support new types, but require the producer and consumer to both understand and follow whatever convention you use. They lack the universal interchangeability of JSON.