2

In my json-schema I have defined a property as

"units":"number"

Now, using JJV validator (a json-schema implimentation), I encounter in my data model a value that is NaN. I would like to do something like this "units":["number","NaN"] instead of doing a custom coercion function like this:

    env.addTypeCoercion('number', function(x){
                if( isNaN(x))
                {
                    return 0
                }
                return x;
            });

The JSON schema primitive types in version 4 seem not to include NaN. How could I devise a schema that allows me to express a property as a number or a NaN?

jruizaranguren
  • 12,679
  • 7
  • 55
  • 73
FlavorScape
  • 13,301
  • 12
  • 75
  • 117

1 Answers1

4

The definition of JSON does not allow NaN values. Therefore any schema for JSON structures which permitted NaN would be permitting things that are not JSON.

If you create JSON using JSON.stringify that includes a NaN value, it will be replaced with null.

Kevin Reid
  • 37,492
  • 13
  • 80
  • 108
  • Ah, looking at JJV implementation, looks like they explicitly intended on not including NaN. `'number': function (x) { // Use x === x instead of !isNaN(x) for speed return typeof (x === 'number' && x === x) },` so I added `|| typeof isNaN(x);` – FlavorScape Oct 23 '14 at 20:28
  • Indeed, JSON does not officially support NaN and Infinity tokens. One big weakness with JSON is that it does not fully support these values despite the fact that they are perfectly valid floating point values that occur all the time in real data. Python's JSON implementation, for good or bad, will emit these tokens by default, so even though it is not technically valid JSON, this does occur quite frequently. – Christopher Barber Jul 19 '22 at 15:27