Git Product home page Git Product logo

json-serializer's Introduction

@brillout/json-serializer

Same as JSON but with added support for:

  • Date
  • undefined
  • Set
  • Map
  • BigInt
  • RegExp
  • NaN
  • Infinity

JSON is a good serializer for JavaScript values but is lacking some JavaScript types such as Date:

const assert = require('assert')

let obj = {
  time: new Date('2042-01-01')
}

// JSON converts dates to strings
assert(obj.time.constructor === Date)
obj = JSON.parse(JSON.stringify(obj))
assert(obj.time.constructor === String)
assert(obj.time === '2042-01-01T00:00:00.000Z')

Whereas with @brillout/json-serializer:

const assert = require('assert')
const { parse } = require('@brillout/json-serializer/parse')
const { stringify } = require('@brillout/json-serializer/stringify')

let obj = {
  time: new Date('2042-01-01')
}

// `@brillout/json-serializer` preserves Date
assert(obj.time.constructor === Date)
obj = parse(stringify(obj))
assert(obj.time.constructor === Date)
assert(obj.time.getTime() === new Date('2042-01-01').getTime())

Contents


Usage

// npm install @brillout/json-serializer
const { parse } = require('@brillout/json-serializer/parse')
const { stringify } = require('@brillout/json-serializer/stringify')

const obj = {
  hello: 'from the future',
  time: new Date('2042-01-01')
}

// Serialize with @brillout/json-serializer
const obj_serialized = stringify(obj)

// Deserialize a @brillout/json-serializer string
const obj_deserialized = parse(obj_serialized)

Full Example

Example exposing all differences between JSON and @brillout/json-serializer.

// /examples/json-serializer.js

const assert = require('assert')

const { parse } = require('@brillout/json-serializer/parse')
const { stringify } = require('@brillout/json-serializer/stringify')

const obj = {
  date: new Date(),
  undefined: undefined,
  NaN: NaN,
  Infinity: Infinity,
  regexp: /^\d+$/g
}

// All of `obj` can be serialized with @brillout/json-serializer
const obj2 = parse(stringify(obj))
assert(obj2.date.getTime() === obj.date.getTime())
assert(obj2.undefined === undefined && 'undefined' in obj2)
assert(isNaN(obj2.NaN))
assert(obj2.Infinity === Infinity)
assert(obj2.regexp.toString() === obj.regexp.toString())

// JSON cannot serialize any of `obj`
const obj3 = JSON.parse(JSON.stringify(obj))
// JSON converts dates to strings
assert(obj3.constructor !== Date)
// JSON removes properties with a value of `undefined`
assert(!('undefined' in obj3))
// JSON converts `NaN` to `null`
assert(obj3.NaN === null)
// JSON converts `Infinity` to `null`
assert(obj3.Infinity === null)
// JSON converts RegExp to an empty object
assert(obj3.regexp.constructor === Object && Object.keys(obj3.regexp).length === 0)

To run the example:

$ git clone [email protected]:brillout/json-serializer
$ cd json-serializer
$ npm install
$ npm run self-link
$ node ./examples/json-serializer.js

The npm run self-link is required to be able to self require('@brillout/json-serializer').


How it Works

Let's see how @brillout/json-serializer serializes an object:

// /examples/inspect.js

const { stringify } = require('@brillout/json-serializer/stringify')

const obj = {
  date: new Date(),
  undefined: undefined,
  collision: '!undefined',
  NaN: NaN,
  Infinity: Infinity,
  regexp: /^\d+$/g
}

console.log(stringify(obj, undefined, 2))
// Prints:
/*
{
  "date": "!Date:2021-01-12T22:15:56.319Z",
  "undefined": "!undefined",
  "collision": "!!undefined"
  "NaN": "!NaN",
  "Infinity": "!Infinity",
  "regexp": "!RegExp:/^\\d+$/g"
}
*/

@brillout/json-serializer is based on JSON while using prefixed strings for unsupported types.

@brillout/json-serializer uses the native JSON.parse and JSON.stringify functions while modifying the serialization of unsupported types.

json-serializer's People

Contributors

brillout avatar cyco130 avatar willparksvg avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

json-serializer's Issues

Support user-defined classes

Allow the user to extend json-serializer with user-defined classes with custom (de-)serialization.

AFAICT it should be fairly easy to implement. PR welcome.

Currently json-serializer behaves like JSON.stringify()/JSON.parse() regarding user-defined classes:

class MyClass {
  prop = 42
}

const obj = new MyClass()
console.log(obj) // MyClass { prop: 42 }
console.log(obj instanceof MyClass) // true

const copy = JSON.parse(JSON.stringify(obj))
console.log(copy) // { prop: 42 }
console.log(copy instanceof MyClass) // false

Licensing?

Hi Rom,

I wasn't able to find any licensing listed for json-s. Did you have an intended license?

Export the `modifier` function

Hey Brillout !
Can you export the modifier function from src/parse.ts as well ?
Then i could use the express json parser with the advanced options like limit, inflate, etc. and use the modifier() function afterwards.

Thx and have a nice coding!

Cannot serialize functions

My vite-ssr app uses vuex on the server side. The vuex store contains state with error objects that have properties pointing to functions. These errors are thrown by APIs and I can't control their structure.

State serialization fails due to the function properties and I see similar errors in the log:

1:21:48 PM [vite] Error when evaluating SSR module /renderer/_default.page.server.ts:
Error: Cannot serialize `foo` because it is a function. Serializer: https://github.com/brillout/json-s
    at Object.replacer (/node_modules/@brillout/json-s/dist/esm/stringify.js:22:19)
    at JSON.stringify (<anonymous>)
    at serializer (/node_modules/@brillout/json-s/dist/esm/stringify.js:11:38)
    at Module.stringify (/node_modules/@brillout/json-s/dist/esm/stringify.js:12:12)
    at /home/node/renderer/_default.page.server.ts:18:100

Would it be possible to make the serialization safe the way that it never throws an error?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.