JSON-S
JSON-Serializer
Same as JSON but with added support for:
Date
undefined
NaN
Inifinity
RegExp
JSON is a great serializer.
But it is lacking for some JavaScript types such as Date
:
const assert = ; let obj = time: '2042-01-01'; // JSON converts dates to strings;obj = JSON;;;
Whereas with JSON-S:
const assert = ;const JSON = ; let obj = time: '2042-01-01'; // JSON-S preserves Date;obj = JSON;;;
Contents
Usage
// npm install json-sconst parse = ;const stringify = ; const obj = hello: 'from the future' time: '2042-01-01'; // Serialize with JSON-Sconst obj_serialized = ; // Deserialize a JSON-S stringconst obj_deserialized = ;
The JSON-S functions stringify
and parse
have the exact same interface than JSON.stringify
and JSON.parse
.
So you can use all JSON's options.
Full Example
Example exposing all differences between JSON and JSON-S.
// /examples/json-s.js const assert = ; const parse = ;const stringify = ; const obj = date: undefined: undefined NaN: NaN Infinity: Infinity regexp: /^\d+$/g; // All of `obj` can be serialized with JSON-Sconst obj2 = ;;;;; // JSON cannot serialize any of `obj`const obj3 = JSON// JSON converts dates to strings;// JSON removes properties with a value of `undefined`;// JSON converts `NaN` to `null`;// JSON converts `Infinity` to `null`;// JSON converts RegExp to an empty object;
To run the example:
$ git clone git@github.com:brillout/json-s$ cd json-s$ npm install$ npm run link$ node ./examples/json-s.js
The npm run link
is required to be able to self require('json-s')
.
How it Works
Let's see how JSON-S serializes an object:
// /examples/inspect.js const JSON = ; const obj = date: undefined: undefined NaN: NaN Infinity: Infinity regexp: /^\d+$/g; // We use the second argument `2` to have a prettified JSON-S string.// (Same as in JSON's `JSON.stringify(obj, undefined, 2)`).console;// Prints:/*{ "date": "json-s:tYpE|Date|2018-11-14T17:39:09.245Z", "undefined": "json-s:tYpE|undefined", "NaN": "json-s:tYpE|NaN", "Infinity": "json-s:tYpE|Infinity", "regexp": "json-s:tYpE|RegExp|/^\\d+$/g"}*/
JSON-S is based on JSON while using prefixed strings for unsupported types.
The string json-s:tYpE
is used as a unique prefix to denote our special strings and make sure that regular strings are not converted.
json-s
uses the native JSON.parse
and JSON.stringify
functions while modifying the serialization of unsupported types.