📦 json-4-ts
json-4-ts is a TypeScript serialization library for encoding and decoding complex JavaScript/TypeScript data structures—including objects, strings, numbers, functions, and symbols—into a structured and deserializable format.
🚀 Features
- Serialize and deserialize:
- Objects
- Strings
- Numbers
- Functions (native and user-defined)
- Symbols
- Custom format with type tagging
- Preserves structure and re-creates function bodies
- Handles unknown and invalid data gracefully
📦 Installation
Since this is a namespace-based library, simply include it in your TypeScript code:
Or manually import the Serializer namespace if modularized.
📘 Usage
Serialize
const obj = {
name: "Alice",
greet: (msg: string) => `Hello, ${msg}`,
id: Symbol("unique")
};
const serialized = Serializer.serialize(obj);
console.log(JSON.stringify(serialized, null, 2));
Deserialize
const restored = Serializer.deserialize(serialized);
console.log(restored.name);
console.log(restored.greet("Bob"));
🧩 API Reference
Serializer.serialize(data: SerializableDataType): SerializedBlock
Serializes supported JavaScript/TypeScript types into a structured block.
Serializer.deserialize(block: SerializedBlock): SerializableDataType
Restores serialized blocks to live runtime objects, functions, or primitives.
🔧 Type Definitions
SerializableDataType
type SerializableDataType =
| Serializable
| Record<string | number | symbol, any>
| string | String
| number | Number
| Function
| symbol | Symbol;
Serializable
type Serializable = {
value: SerializableDataType;
};
SerializedBlock
type SerializedBlock = {
type: string;
value: SerializedBlockType;
};
SerializedBlockType
type SerializedBlockType =
| ContextBlock
| StringBlock
| NumberBlock
| ObjectBlock
| FunctionBlock
| SymbolBlock
| null;
Specialized Block Types
StringBlock
type StringBlock = {
string: string;
};
NumberBlock
type NumberBlock = {
number: number;
};
ObjectBlock
type ObjectBlock = {
object: Record<string | number | symbol, SerializedBlock>;
};
FunctionBlock
type FunctionBlock = {
function: string;
context: ContextBlock;
};
SymbolBlock
type SymbolBlock = {
symbol: string;
};
ContextBlock
type ContextBlock = {
context: {
this: any;
};
};
🧠 Symbols
The following symbols are used for fallback states:
Serializer.unknown
Serializer.invalid
unknown: Used when a function cannot be serialized
invalid: Returned if deserialization fails
🧪 Example
const data = {
n: 42,
message: "Hello",
run: (x: number) => x + 1,
flag: Symbol("secret")
};
const s = Serializer.serialize(data);
console.log(s);
const restored = Serializer.deserialize(s);
console.log(restored.run(5));
⚠️ Limitations
- Function serialization is based on
toString() and may not preserve closure scope
- Native functions may only serialize by name (if they can be resolved with
eval)
- The
"this" context is stored as null during serialization
- Symbols are stored as strings (description only)
📄 License
MIT License