Skip to content

Better support for null values #130

@marcbachmann

Description

@marcbachmann

I ran into an issue with the serialization of values I query from a postgres database.
The behavior in fast-json-stringify is currently not documented and there's no mention anywhere about how non-matching input values behave, so I guess this topic didn't come up yet (at least not on github).

We should be able to provide a good solution for the problem, be it dropping the properties, throw an error or coerce the value to something else and then also document that.

With ajv and json-schema, such multi-type values are supported with type: ["string", "null"], optionally in combination with an anyOf declaration.
Maybe we could support something similar in this library.

> node -p "(new (require('ajv'))).validate({type: ['string', 'null']}, 'string')"
true

> node -p "(new (require('ajv'))).validate({type: ['string', 'null']}, null)"
true

This topic already came up for strings in #41, but there's no mention of other types. It got fixed by coercing the value to an empty string whereas for the other types the behavior is still not defined.

> node -p "require('fast-json-stringify')({type: 'string'})(null)"
""

Integers:

> node -p "require('fast-json-stringify')({type: 'integer'})(null)"
0

Objects:

> node -p "require('fast-json-stringify')({type: 'object'})(null)"
undefined:62
      var obj = typeof input.toJSON === 'function'
                             ^
TypeError: Cannot read property 'toJSON' of null
    at $main (eval at build (/repo/node_modules/fast-json-stringify/index.js:118:20), <anonymous>:62:30)
    at [eval]:1:49
    at ContextifyScript.Script.runInThisContext (vm.js:50:33)
    at Object.runInThisContext (vm.js:139:38)
    at Object.<anonymous> ([eval]-wrapper:6:22)
    at Module._compile (module.js:653:30)
    at evalScript (bootstrap_node.js:479:27)
    at startup (bootstrap_node.js:180:9)
    at bootstrap_node.js:625:3

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions