1.0.1 • Published 1 year ago

lzo-jsonex v1.0.1

Weekly downloads
-
License
MIT
Repository
github
Last release
1 year ago

LZO: JsonEx

Data Serializer and Deserializer.

Sponsor Commitizen friendly TypeScript version Node.js version MIT Build Status - GitHub Actions

Installation

npm install lzo-jsonex OR yarn add lzo-jsonex

Usage

Just

import { JsonEx } from 'lzo-jsonex';

const jsonEx = new JsonEx({});

const obj = jsonEx.stringify({ a: 1, b: 2, c: 3 });
const arr = jsonEx.stringify([1, 2, 3]);
const int = jsonEx.stringify(2023);
const bol = jsonEx.stringify(true);
const str = jsonEx.stringify('John Doe');

console.log(jsonEx.parse(obj), typeof jsonEx.parse(obj)); // { a: 1, b: 2, c: 3 } object
console.log(jsonEx.parse(arr), typeof jsonEx.parse(arr)); // [1, 2, 3] object
console.log(jsonEx.parse(int), typeof jsonEx.parse(int)); // 2023 number
console.log(jsonEx.parse(bol), typeof jsonEx.parse(bol)); // true boolean
console.log(jsonEx.parse(str), typeof jsonEx.parse(str)); // John Doe string
import { JsonEx } from 'lzo-jsonex';

class Person {
  constructor(private name: string) { }

  public getName() {
    return this.name;
  }

  public setName(name: string) {
    this.name = name;
  }
}

const jsonEx = new JsonEx({
  Person,
});

const person = new Person('John Doe');

const compressed = jsonEx.stringify(person); // Uint8Array
const decompressed = jsonEx.parse(compressed); // Person
console.log(decompressed.getName()) // John Doe

// ! Maintains class integrity

decompressed.setName('Jane Doe');
const compressed2 = jsonEx.stringify(decompressed); // Uint8Array
const decompressed2 = jsonEx.parse(compressed2); // Person
console.log(decompressed2.getName()) // Jane Doe

Maintaining Inheritance

import { JsonEx } from 'lzo-jsonex';

class Person {
  constructor(protected name: string) { }

  public getName() {
    return this.name;
  }

  public setName(name: string) {
    this.name = name;
  }
}

class Hero extends Person {
  constructor(protected name: string, protected power: string) {
    super(name);
  }

  public getPower() {
    return this.power;
  }
}

const jsonEx = new JsonEx({
  Person,
  Hero,
});

const person = new Hero('John Doe', 'Super Strength');

const compressed = jsonEx.stringify(person); // Uint8Array
const decompressed = jsonEx.parse<Hero>(compressed); // Person
console.log(decompressed.getName()) // John Doe
console.log(decompressed.getPower()) // Super Strength

API

JsonEx.getMaxDepth(): number

Get the maximum depth of the object

JsonEx.makeDeepCopy<T>(object: T): T

Make a deep copy of the object

JsonEx.stringify<T>(value: T): Uint8Array

Stringify the object to Uint8Array

JsonEx.parse<T>(json: Uint8Array): T

Parse the Uint8Array to object maintaining the prototype chain

Backers & Sponsors

Support this project by becoming a sponsor.

License

Licensed under the MIT. See the LICENSE file for details.

1.0.1

1 year ago