1.0.0 • Published 15 days ago

jsonesc v1.0.0

Weekly downloads
8
License
Apache-2.0
Repository
github
Last release
15 days ago

Json Escape

Json Escape use escape character in string to store types that normally not allowed in JSON

unicode character 0x362 is used for the escaping

examples

// import JsonEsc from 'jsonesc';
const JsonEsc = require('jsonesc').default;

JsonEsc.stringify( [
  NaN,
  -Infinity,
  new Date(),
  new Uint8Array([1,2,3,4])
], 1);
// returns:
[
 "͢NaN",
 "͢-Inf",
 "͢Date:2018-02-07T19:07:18.207Z",
 "͢Bin:wFg{A"
]

Advantage

JsonEsc allows additional data types to be serialized in JSON, such as binary date (Uint8Array) and Date, while still keeps the verbose nature of JSON. The output string is still a 100% valid JSON, and compatible with any JSON editing/parsing tool or library. This makes JsonEsc much easier to debug and trouble shoot than binary formats like BSON and MsgPack

Performance

Modern browsers and nodejs are hightly optimized for JSON. This allows JsonEsc to be encoded and decoded faster than the other 2 formats in most of the cases.

benchmark result

Benchmark with sample data on Chrome 77, Firefox 69

Time are all in ms, smaller is better

ChromeEncodeChromeDecodeFirefoxEncodeFirefoxDecode
JsonEsc0.14340.17420.17080.1301
MsgPack0.28930.18180.66890.1933
BSON0.15730.18790.39450.5648

API

JsonEsc.stringify(inpt:any, space?:number, sortKeys?:boolean = false);
JsonEsc.parse(inpt:string);

Custom Types

JsonEsc's register API make it really simple to add custom type into json encoding/decoding

// custom type
class MyClass {
  constructor(str) {
    this.myStr = str;
  }
}

let myJson = new JsonEsc();
myJson.register('My', MyClass,
  // custom encoder
  (obj) => obj.myStr,
  // custom decoder
  (str) => new MyClass(str)
);

myJson.stringify(new MyClass("hello"));
// "͢My:hello"

Base93 encoding

JsonEsc use Base93 by default to encode binary data, it's more compact than Base64.

If you prefer Base64, set binaryFormat to base64 in the JsonEsc constructor

const JsonEsc = require('jsonesc').default;

const myJson = new JsonEsc({binaryFormat: 'base64'});

myJson.stringify({binary: new Uint8Array([1,2,3,4])});
// {"binary":"͢B64:AQIDBA=="}
1.0.0

15 days ago

0.4.13

2 months ago

0.4.12

2 years ago

0.4.11

4 years ago

0.4.10

4 years ago

0.4.9

4 years ago

0.4.8

4 years ago

0.4.7

4 years ago

0.4.6

5 years ago

0.4.5

5 years ago

0.4.4

5 years ago

0.4.3

5 years ago

0.4.2

6 years ago

0.4.1

6 years ago

0.4.0

6 years ago

0.3.0

6 years ago

0.2.0

6 years ago

0.1.0

6 years ago

0.0.1

6 years ago