Security News
ESLint is Now Language-Agnostic: Linting JSON, Markdown, and Beyond
ESLint has added JSON and Markdown linting support with new officially-supported plugins, expanding its versatility beyond JavaScript.
Typeson is a JavaScript library that allows you to serialize and deserialize complex data types to and from JSON. It extends the capabilities of JSON.stringify and JSON.parse to handle more complex data structures such as Dates, Maps, Sets, and more.
Serialization and Deserialization
Typeson allows you to serialize and deserialize complex data types like Date objects. The example shows how to serialize an object containing a Date and then deserialize it back to its original form.
const Typeson = require('typeson');
const typeson = new Typeson();
const obj = { date: new Date() };
const serialized = typeson.stringify(obj);
const deserialized = typeson.parse(serialized);
console.log(serialized); // Output: {"date":"2023-10-05T14:48:00.000Z"}
console.log(deserialized); // Output: { date: 2023-10-05T14:48:00.000Z }
Custom Type Handlers
Typeson allows you to define custom type handlers for serialization and deserialization. The example demonstrates how to handle RegExp objects by defining custom test, replace, and revive functions.
const Typeson = require('typeson');
const typeson = new Typeson();
// Define a custom type handler for RegExp
const regExpType = {
test: x => x instanceof RegExp,
replace: x => x.toString(),
revive: x => new RegExp(x.slice(1, x.lastIndexOf('/')), x.slice(x.lastIndexOf('/') + 1))
};
// Register the custom type handler
typeson.register({ RegExp: regExpType });
const obj = { pattern: /abc/i };
const serialized = typeson.stringify(obj);
const deserialized = typeson.parse(serialized);
console.log(serialized); // Output: {"pattern":"/abc/i"}
console.log(deserialized); // Output: { pattern: /abc/i }
Handling Circular References
Typeson can handle circular references in objects. The example shows how to serialize and deserialize an object with a circular reference using Typeson's circular preset.
const Typeson = require('typeson');
const typeson = new Typeson.Typeson().register(Typeson.presets.circular);
const obj = {};
obj.self = obj;
const serialized = typeson.stringify(obj);
const deserialized = typeson.parse(serialized);
console.log(serialized); // Output: {"self":"~"}
console.log(deserialized); // Output: { self: [Circular] }
Flatted is a lightweight library for serializing and deserializing JavaScript objects with circular references. Unlike Typeson, Flatted focuses specifically on handling circular references and does not support custom type handlers or complex data types like Dates or Maps.
CircularJSON is another library for serializing and deserializing objects with circular references. It is similar to Flatted but has a different API. CircularJSON also does not support custom type handlers or complex data types, making it less versatile than Typeson.
SuperJSON is a library that extends JSON to support more complex data types like Dates, Maps, and Sets. It is similar to Typeson in its ability to handle complex data structures, but it does not offer the same level of customization for defining custom type handlers.
JSON with type info
JSON can only contain simple types: strings, numbers, booleans, Arrays and Objects. In case you want to serialize a Date or an Error object for example, you will need fix that manually. Typeson is just JSON that complements non-trivial properties with type info. The metadata is a $types property in the result that maps each non-trivial property to a type name. You can configure the registry of type names and defines how to encapsulate and revive custom types.
var typeson = new Typeson([options]);
// Use it exactly like JSON.stringify()
var tson = typeson.stringify({date: new Date(), rex: new RegExp()});
// Parse exactly like JSON.parse()
var parsed = typeson.parse(tson);
Creates an instance of Typeson, on which you may configure additional types to support, or call stringify() or parse() on.
{ cyclic?: boolean, // Default true types?: {TypeName: [tester, encapsulator, reviver]} // Defaults to the built-in types (currently Date, RegExp and Error) }
Whether or not to support cyclic references. Default true unless explicitely set to false. If this property is false, the parsing algorithm becomes a little faster and in case a single object occurs on multiple properties, it will be duplicated in the output (as JSON.stringify() would do). If this property is true, several instances of same object will only occur once in the generated JSON and other references will just contain a pointer to the single reference.
A map of {TypeName: string => [tester, encapsulator reviver].
Function that tests whether an instance is of your type and returns a truthy value if it is.
Function that maps you instance to a JSON-serializable object.
Function that maps you JSON-serializable object into a real instance of your type.
var typeson = new Typeson();
var tson = typeson.stringify(complexObject);
console.log(tson);
var obj = typeson.parse(tson);
Generates JSON based on given obj. If given obj has special types or cyclic references, the produce JSON will contain a $types property on the root where type info relies.
new Typeson().stringify ({date: new Date()})
Output:
{"date": 1463667643065, "$types": {"date": "Date"}}
Parses Typeson genereted JSON back into the original complex structure again.
new Typeson().parse ('{"date": 1463667643065, "$types": {"date": "Date"}}');
{TypeName: [tester, encapsulator, reviver]}
var typeson = new Typeson();
typeson.register({
DateObject: [
x => x instanceof Date, // tester
date => date.getTime(), // encapsulator
obj => new Date(obj) // reviver
],
RegularExpression: [
x = x instanceof RegExp,
re => ({source: re.source, flags: re.flags}),
o => new RegExp (o.source, o.flags)
]
});
FAQs
Preserves types over JSON, BSON or socket.io
We found that typeson demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 2 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
ESLint has added JSON and Markdown linting support with new officially-supported plugins, expanding its versatility beyond JavaScript.
Security News
Members Hub is conducting large-scale campaigns to artificially boost Discord server metrics, undermining community trust and platform integrity.
Security News
NIST has failed to meet its self-imposed deadline of clearing the NVD's backlog by the end of the fiscal year. Meanwhile, CVE's awaiting analysis have increased by 33% since June.