tiny.json is a schema base json stringify.
it's use schema to generated code. so it's significantly faster than JSON.stringify() with small payload.
and since it stringify with schema is also more secure.
Build a stringify() function based on
jsonschema. for now this implementation only support 'type' & 'default'.
If value is null or undefined the 'default' whill be used.
otherwise value.toJSON() or value.toString() will be used.
Sample
{
type: 'string',
default: '"hello"'
}
// notice the `default` need has `"` included, for nowIf value is null or undefined the 'default' whill be used.
otherwise, will use !!(value) to enforce to got true|false as result.
Sample
{
type: 'boolean',
default: null
}Result as parseFloat(value) if isFinite otherwise default whill be used.
Sample
{
type: 'number',
default: 100
}Result as parseInt(value) if isFinite otherwise default whill be used.
Sample
{
type: 'integer',
default: 200
}use properties to declare propertie, all type can nested.
Sample
// {"text":"hello", flag: false}
{
type: 'object',
properties: {
text: { type: 'string'},
flag: { type: 'boolean'}
}
}Sample
// [1,2,3,4]
{
type: 'array',
items: {
type: 'integer'
}
}
// [{a:1},{a:2}]
{
type: 'array',
items: {
type: 'object',
properties: {
a: { type: 'number'}
}
}
}
// [1, 2, false, "hello"]
{
type: 'array'
}NOTE: tiny.json won't perform any string escaping as is could be a performance impact. escaping may happend before stringify and stored as escaped.
you can useing JSON.stringify or regex as your need
Sample
// with JSON.stringify.
JSON.stringify('hello "world"'); // hello \"world\"
// with regex.
'hello "world"'.replace(/\n|\r|\t|\"|\\/gm, char => '\\' + char) // hello \"world\"Checkout benchmarks code
native x 1,720,071 ops/sec ±0.25% (91 runs sampled)
tiny x 60,489,145 ops/sec ±1.66% (89 runs sampled)
# tiny is +3416.67% fasterthe payload and schema for this benchmark
const obj = {
hello: 'world',
num: 20190522,
flag: true
};
const tiny = createStringify({
type: 'object',
properties: {
hello: {
type: 'string'
},
num: {
type: 'number'
},
flag: {
type: 'boolean'
}
}
});