Coder Social home page Coder Social logo

tupleson's Introduction

tupleSON

Your hackable JSON serializer/deserializer

All Contributors: 2 Codecov Test Coverage Contributor Covenant License: MIT Style: Prettier TypeScript: Strict


Customizable serialization & deserialization. Serialize almost1 anything!

๐ŸŽฏ Project Goals

  • ๐Ÿ’ก JSON-compatible output
  • ๐Ÿ“– Human-readable output
  • ๐Ÿ”ง Customizable behavior โ€“ tailor it to your exact needs
  • ๐ŸŒŠ Serialize & stream things like Promises or async iterators

Important

Though well-tested, this package might undergo big changes and does not follow semver whilst on 0.x.y-version, stay tuned!

๐Ÿ‘€ Example

/* eslint-disable @typescript-eslint/no-unused-vars, n/no-missing-import */

import {
	// Create serializer / deserializer
	createTson,
	// Serialize `bigint`
	tsonBigint,
	// Serialize `Date`
	tsonDate,
	// Serialize `Map`s
	tsonMap,
	// **throws** when encountering Infinity or NaN
	tsonNumberGuard,
	// Serialize regular expression
	tsonRegExp,
	// Serialize `Set`s
	tsonSet,
	// serialize a Symbol
	tsonSymbol,
	// Serialize `URL`s
	tsonURL,
	// Serialize `undefined`
	tsonUndefined,
	// **throws** when encountering non-registered complex objects (like class instances)
	tsonUnknownObjectGuard,
} from "tupleson";

const tson = createTson({
	/**
	 * The nonce function every time we start serializing a new object
	 * Should return a unique value every time it's called
	 * @default `${crypto.randomUUID} if available, otherwise a random string generated by Math.random`
	 */
	// nonce: () => "__tson",
	types: [
		// Pick which types you want to support
		tsonSet,
	],
});

const myObj = {
	foo: "bar",
	set: new Set([1, 2, 3]),
};

const str = tson.stringify(myObj, 2);
console.log(str);
// (๐Ÿ‘€ All non-JSON values are replaced with a tuple, hence the name)

// ->
// {
//   "json": {
//     "foo": "bar",
//     "set": [
//       "Set",
//       [
//         1,
//         2,
//         3
//       ],
//       "__tson"
//     ]
//   },
//   "nonce": "__tson"
// }

const obj = tson.parse(str);

// โœจ Retains type integrity
type Obj = typeof obj;
//   ^?
// -> type Obj = { foo: string; set: Set<number>; }

๐Ÿคฏ Streaming Promises and AsyncIterables

๐Ÿงฉ Extend with a custom serializer

Important

When defining custom serializers, the array order matters! If a value passes the test for more than one custom serializer, the first wins.

โŒš๏ธ Temporal

See test reference in ./src/extend/temporal.test.ts

/* eslint-disable @typescript-eslint/no-unused-vars, n/no-missing-import, n/no-unpublished-import */
import { Temporal } from "@js-temporal/polyfill";
import { TsonType, createTson } from "tupleson";

const plainDate: TsonType<Temporal.PlainDate, string> = {
	deserialize: (v) => Temporal.PlainDate.from(v),
	key: "PlainDate",
	serialize: (v) => v.toJSON(),
	test: (v) => v instanceof Temporal.PlainDate,
};

const instant: TsonType<Temporal.Instant, string> = {
	deserialize: (v) => Temporal.Instant.from(v),
	key: "Instant",
	serialize: (v) => v.toJSON(),
	test: (v) => v instanceof Temporal.Instant,
};

const tson = createTson({
	types: [plainDate, instant],
});

๐Ÿงฎ Decimal.js

See test reference in ./src/extend/decimal.test.ts

/* eslint-disable @typescript-eslint/no-unused-vars, n/no-missing-import, n/no-unpublished-import */
import { Decimal } from "decimal.js";

const decimalJs: TsonType<Decimal, string> = {
	deserialize: (v) => new Decimal(v),
	key: "Decimal",
	serialize: (v) => v.toJSON(),
	test: (v) => v instanceof Decimal,
};

const tson = createTson({
	types: [decimalJs],
});

๐Ÿ’™ This package is based on @JoshuaKGoldberg's create-typescript-app.

Footnotes

  1. ๐ŸŒ€ Circular references not your thing? We agree & we don't support it. But hey, feel free to make a PR add opt-in support for that if you need it! โ†ฉ

tupleson's People

Contributors

helmturner avatar juliusmarminge avatar katt avatar sachinraja avatar sheraff avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.