fast-json-stringify icon indicating copy to clipboard operation
fast-json-stringify copied to clipboard

TypeCoercion like ajv

Open Uzlopak opened this issue 2 years ago • 5 comments

Prerequisites

  • [X] I have written a descriptive issue title
  • [X] I have searched existing issues to ensure the issue has not already been raised

Issue

In my opinion, we should do the same type coercion like ajv does.

https://ajv.js.org/coercion.html

Uzlopak avatar Feb 24 '23 13:02 Uzlopak

To what end? AJV is coercing JSON into JavaScript natives. FJS is converting JavaScript natives into JSON.

jsumners avatar Feb 24 '23 13:02 jsumners

const fastJson = require('fast-json-stringify')

const stringify = fastJson({
  title: 'Example Schema',
  type: 'object',
  properties: {
    boolean: {
      type: 'boolean'
    }
    }
})

console.log(stringify({
    boolean: "false"
}))

results in "{\"boolean\":true}"

awesome

Uzlopak avatar Feb 24 '23 14:02 Uzlopak

Not a good example IMHO. With the same result, you can complain about the js standard. !!"false" === true

but I also don't like some types coercions that we have. The question is what should we do in this case?

  • throw an error
  • return { boolean: "false" }
  • return { boolean: false }
  • return { boolean: true } return {}

ivan-tymoshenko avatar Feb 24 '23 14:02 ivan-tymoshenko

The risk that I see here is about diverging behaviour between ajv and fsj. Then we have some cases were ajv validates as valid and fsj maybe throws or serializes it differently. Also we potentially need to coerce the vaues if we want to process them for stuff like const and enum. If we want to go that way.

Uzlopak avatar Feb 24 '23 14:02 Uzlopak

I'm pro to good coercion default and not throwing.

Eomm avatar Feb 26 '23 16:02 Eomm