JSOG for TypeScript

1.0.0-1 · active · verified Sun Apr 19

jsog-typescript is a TypeScript module that implements the JavaScript Object Graph (JSOG) format, enabling the serialization and deserialization of JavaScript objects while preserving object references to prevent cycles and duplicates. Its key differentiator is the ability to instantiate actual TypeScript class instances during deserialization, leveraging decorators for type mapping. This allows developers to work with rich object models that retain their methods and `typeof` information after being processed. The package is currently at version 1.0.0-1 and appears to be actively maintained, offering specific integration patterns for frameworks like Angular 4 and AngularJS. It builds upon the core JSOG specification and incorporates ideas from `json-typescript-mapper` to provide this type-aware deserialization.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates defining TypeScript classes with `@JsonProperty` decorators, serializing an object graph including circular references, and then deserializing it back into full TypeScript class instances, preserving methods and `instanceof` checks.

import { jsogService, JsonProperty, JsogService } from 'jsog-typescript';
import 'reflect-metadata'; // Essential for decorators to work at runtime

// 1. Define a TypeScript class with decorators
class Address {
  @JsonProperty() street: string = '';
  @JsonProperty() city: string = '';

  getFullAddress(): string {
    return `${this.street}, ${this.city}`;
  }
}

class Person {
  @JsonProperty() id: number = 0;
  @JsonProperty() name: string = '';
  @JsonProperty(Address) address: Address | undefined;
  @JsonProperty(Person) friends: Person[] = []; // Array of nested custom objects

  greet(): string {
    return `Hello, my name is ${this.name}!`;
  }
}

// 2. Instantiate and serialize an object graph
const person1 = new Person();
person1.id = 1;
person1.name = 'Alice';
person1.address = new Address();
person1.address.street = '123 Main St';
person1.address.city = 'Anytown';

const person2 = new Person();
person2.id = 2;
person2.name = 'Bob';
person2.friends.push(person1); // Create a circular reference

person1.friends.push(person2);

const serializedGraph = jsogService.serialize(person1);
console.log('Serialized Graph:', JSON.stringify(serializedGraph, null, 2));

// 3. Deserialize back into TypeScript objects
const deserializedPerson = jsogService.deserializeObject(serializedGraph, Person);

console.log('\nDeserialized Person:', deserializedPerson);
console.log('Is instance of Person:', deserializedPerson instanceof Person); // true
console.log('Is instance of Address:', deserializedPerson.address instanceof Address); // true
console.log('Person greeting:', deserializedPerson.greet());
console.log('Person address:', deserializedPerson.address?.getFullAddress());
console.log('Friend greeting:', deserializedPerson.friends[0]?.greet());

view raw JSON →