JSON
elements man jsonElements ships with its own JSON serializer. The output is valid JSON, so
any JSON parser can read it, and the format also records an object's
class, cycles, and repeated references. Standard JSON doesn't handle
any of those. A class like User arrives on the browser as a plain
object, without instanceof User or any methods. A graph containing a
cycle throws. Shared subgraphs serialize their inner objects over and
over.
Elements JSON handles all three. A class marked with the @json
decorator round-trips with its identity intact: the same User instance
leaves the server and arrives on the browser as a User instance.
Repeated references serialize once and back-reference on every subsequent
appearance. Cycles round-trip without infinite recursion. Date, Map,
Set, SqlResult, LiveTable, Listener, and File all have built-in
handlers that preserve their type.
Elements uses this serializer automatically wherever data moves between the
server and the browser. You don't call stringify() yourself; Elements does
it in each of these places:
@rpcarguments and return values.- Route handler returns from
route()to the HTML page. - Plain objects and arrays returned from API route handlers.
Channel.notify(...)payloads and listener messages.LiveTablebroadcasts.
Mark a custom class @json and an instance sent in any of those places
is rebuilt by the receiver as an instance of the same class. To get the
JSON string yourself, call stringify() and parse() directly.
Usageimport { stringify, parse } from "@elements/app"; let s = stringify(value); // EJSON string let v = parse(s); // value with class identity restored
At a Glance
Exampleimport { json, stringify, parse } from "@elements/app"; json class User { id: string; name: string; createdAt: Date; constructor(id: string = "", name: string = "", createdAt: Date = new Date()) { this.id = id; this.name = name; this.createdAt = createdAt; } } let user = new User("u1", "alice", new Date()); let s = stringify(user); // EJSON string let u: User = parse(s); // round-trips with class identity intact u instanceof User; // true u.createdAt instanceof Date; // true
The @json Decorator
@json is a TypeScript decorator. Apply it to any class you want to
round-trip through Elements JSON with its class identity intact.
Exampleimport { json } from "@elements/app"; json class Comment { id: string; text: string; author: string; }
Without @json, a class instance serializes as a plain JSON object. The
browser receives a plain object, not an instance of the class, so
instanceof is false and the class's methods are missing. A class you
only read fields from needs no decorator. Use @json when you want class identity preserved.
The decorator registers the class by name in a global registry. The
serializer emits { "$type": "<class name>", "$value": { ... } }. The
deserializer looks up the class and reconstructs the instance.
What the Serializer Handles
null,undefined,boolean,number,string: passed through.Date: emitted as{ "$type": "Date", "$value": <epoch millis> }.Map,Set: emitted with their entries preserved.Array,Object: recursive.- Repeated reference: emitted as
{ "$type": "ref", "$value": "<path>" }. The serializer emits the value once and refs it on subsequent appearances. - Cycles: resolved via
ref. A node referencing itself, directly or transitively, round-trips without infinite recursion. @json-decorated class instances: emitted as{ "$type": "<name>", "$value": { ... } }.SqlResult,Listener,LiveTable,File: built-in types with their own handlers. ASqlResultreturned from an@rpcarrives on the browser as aSqlResult, sofirst(),all()and iteration work there too.
Custom Serialization
To control the JSON value a class serializes to, implement the
[ToJSON] and [FromJSON] symbols.
Exampleimport { json, ToJSON, FromJSON, JSONType } from "@elements/app"; interface MoneyJSON { c: number; ccy: string; } json class Money { cents: number; currency: string; constructor(cents: number = 0, currency: string = "USD") { this.cents = cents; this.currency = currency; } [ToJSON]() { return { c: this.cents, ccy: this.currency, }; } static [FromJSON](value: MoneyJSON): Money { return new Money(value.c, value.ccy); } static [JSONType]() { return "Money"; } }
[ToJSON](): instance method that returns the value written to$value. The default copies own properties.[FromJSON](/man/value): static method that reconstructs the instance. The default doesObject.assign(new Class(), value).[JSONType](): static method that returns the type name written to$type. The default is the class name.
Once the class is registered via @json, the serializer calls [ToJSON]
and the deserializer calls [FromJSON]. You do not call them yourself.
Helpers
Usageimport { stringify, parse, serialize, deserialize } from "@elements/app"; let s = stringify(value); // EJSON string let v = parse(s); // round-trip let s2 = serialize(value, replacer, " "); // JSON.stringify-style options let v2 = deserialize(s2);
stringify and serialize are aliases. parse and deserialize are aliases.
The replacer and space arguments mirror JSON.stringify. The
replacer runs after Elements has computed the type tag, so the value it
receives is the { "$type": ..., "$value": ... } object.
To pass a space (indent) without a replacer, pass undefined for the
replacer, not null:
Examplelet pretty = stringify(value, undefined, " "); // indented, no replacer
Attach
After deserialization, classes that need setup after they are built implement an
[Attach]() method. The deserializer calls [Attach]() on each
instance after the entire graph has been reconstructed and references are
resolved.
In the browser, a Listener uses [Attach]() to send its listen request to
the server, and a LiveView uses it to start applying the changes its
listener receives. Application classes can implement it too if they need
the same kind of post-deserialization setup.
Related
rpc: arguments and return values are serialized with this serializer.router: the values a route handler passes to an HTML page, and the objects an API route returns, are serialized with this serializer.livetable: broadcasts use this serializer.channel: notify payloads use this serializer.