serialize-anything

serialize and de-serialize any JavaScript data

Usage no npm install needed!

<script type="module">
  import serializeAnything from 'https://cdn.skypack.dev/serialize-anything';
</script>

README

serialize-anything

A universal serializer and de-serializer for JavaScript data

GitHub top language GitHub package.json version codebeat badge David NPM Downloads NPM License Twitter

Overview

serialize-anything serializes and de-serializes virtually all JavaScript standard and custom data types, with no data modification.

Compared to commonly used serialize/deserialze methods which convert only a subset of JavaScript data types — serialize-anything converts more without loss of any data.

Exceptions

  1. There are two JavaScript types that serialize-anything does not support: WeakMap and WeakSet. Since there is no known way to enumerate their values, they can't be serialized.

  2. Circular object references are not supported at this time.


Data Types Supported

Comparing support for data types in the most popular methods.

Legend:     ❌ - Error     🗑 - data loss     ✅ - correct

Data Type JSON.* s-javascript s-to-js s-anything
Date 🗑
RegExp 🗑
Buffer 🗑 🗑
Error 🗑 🗑
BigInt 🗑
undefined
{prop: undefined} 🗑
TypedArray 🗑 🗑
Map 🗑
Set 🗑
Custom Object 🗑 🗑 🗑
Custom Array 🗑 🗑 🗑
BigInt64Array 🗑
BigUint64Array 🗑
Function
ArrayBuffer 🗑
WeakSet 🗑 🗑
WeakMap 🗑 🗑
Circular reference

      JSON.* — JSON.stringify/parse
      s-javascript — serialize-javascript
      s-to-js — serialize-to-js
      s-anything — serialize-anything


Installation

Install as a Node.js module:

 $ npm install serialize-anything

Or download a package from github.

Usage

Node.js:

const SerAny = require('serialize-anything');

// copied from `custom-objects.js` to handle custom objects (optional)
SerAny._custom = function (name) {
  let typeExists = eval('typeof ' + name + '!== "undefined"' );
  return typeExists ? eval('new ' + name + '()') : null;
};
SerAny._ds = SerAny.deserialize;
SerAny.deserialize = source => SerAny._ds(source, SerAny._custom);

From HTML file:

<script src="serialize-any.js"></script>
<script>
    // copied from `custom-objects.js` to handle custom objects (optional)
    SerAny._custom = function (name) {
      let typeExists = eval('typeof ' + name + '!== "undefined"' );
      return typeExists ? eval('new ' + name + '()') : null;
    };
    SerAny._ds = SerAny.deserialize;
    SerAny.deserialize = source => SerAny._ds(source, SerAny._custom);
</script>

To serialize:

// serialize
serialized = SerAny.serialize(source);

To deserialize:

// deserialize
deserialized = SerAny.deserialize(serialized);

Example

Serialize some challenging data:

const custom = new CustomObj();
custom.foo = 'bar';
let source = {
  undef: undefined,
  regexp: /abc/gi,
  bignum: 4000000000000000000n,
  map: new Map([[1, 'one'], [2, 'two']]),
  custom,
  buffer: Buffer.from("hello world")
};

/* source:
{
  undef: undefined,
  regexp: /abc/gi,
  bignum: 4000000000000000000n,
  map: Map(2) { 1 => 'one', 2 => 'two' },
  custom: CustomObj { foo: 'bar' },
  buffer: <Buffer 68 65 6c 6c 6f 20 77 6f 72 6c 64>
}
*/

const ser = SerAny.serialize(source);

Serialized result (JSON):

{
  "_Serialize_Any_Encoded": true,
  "_SA_Content": {
    "undef": { "_SAType": "undef" },
    "regexp": {
      "_SAType": "RegExp",
      "_SAsource": "abc",
      "_SAflags": "gi"
    },
    "bignum": {
      "_SAType": "BigInt",
      "_SAnum": "4000000000000000000"
    },
    "map": {
      "_SAType": "Map",
      "_SAkvPairs": [ [1, "one"], [2,"two"] ]
    },
    "custom": {
      "_SAType": "_SACustomObject",
      "_SAconstructorName": "CustomObj",
      "_SAobject": { "foo": "bar" }
    },
    "buffer": {
      "_SAType": "Buffer",
      "_SAutf8String": "hello world"
    }
  }
}

Deserialized:

const deser = SerAny.deserialize(ser);

/* deser:
{
  undef: undefined,
  regexp: /abc/gi,
  bignum: 4000000000000000000n,
  map: Map(2) { 1 => 'one', 2 => 'two' },
  custom: CustomObj { foo: 'bar' },
  buffer: <Buffer 68 65 6c 6c 6f 20 77 6f 72 6c 64>
}
*/

Functions

SerAny.serialize()

Serialize JavaScript data

Syntax

SerAny.serialize(source [, options])

Parameters

source
    The JavaScript data to serialize

options
    (Object) [optional] - Control the serializer's behavior.

options properties:

    maxDepth
       (number) [optional] - Limit the number of levels
       into the source data. Throws an error if source's
       depth is greater than maxDepth. Default is 20 levels.

    pretty
       (boolean) [optional] - Return serialized data in
       pretty format if true. Default is false - not pretty.

Return value

(string) - The serialized data.


SerAny.deserialize()

Restore serialized data created by SerAny.serialize().

Syntax

SerAny.deserialize(source)

Parameters

source
    (string) - Serialized data that was created by SerAny.serialize()

Return value

(any type) - The de-serialized data, matching the type of the original source.