JSON numbers (was: Revisiting Decimal)

David-Sarah Hopwood david.hopwood at industrial-designers.co.uk
Thu Jan 15 18:07:33 PST 2009


Brendan Eich wrote:
> On Jan 14, 2009, at 7:38 PM, Kris Zyp wrote:
> 
>>>> You need to change this in any case, since even though the JSON
>>> RFC allows arbitrary precision decimal literals, real-world
>>> decoders only decode into IEEE doubles. You'd have to encode
>>> decimals as strings and decode them using domain-specific (JSON
>>> schema based) type knowledge.
>> No, every Java JSON library I have seen
> 
> You've seen
> 
> http://www.json.org/json2.js
> 
> It and the json.js alternative JS implementation are popular. json2.js
> contains
> 
>         String.prototype.toJSON =
>         Number.prototype.toJSON =
>         Boolean.prototype.toJSON = function (key) {
>             return this.valueOf();
>         };
> 
>> parses (at least some, if not
>> all) numbers to Java's BigDecimal.
> 
> JSON has nothing to do wth Java, and most implementations do not have
> Java BigDecimal, so I don't know how it can be relevant.

There seems to be a misconception here.

JSON is a general-purpose data description language. It happens to have
a syntax that is *almost* (see below) a subset of ECMAScript's syntax,
but it was explicitly designed to be useful across languages, and for
data formats that are specified independently of programming language.
The de facto bindings of JSON to other languages are therefore just
as relevant as its bindings to ECMAScript, in determining what its
de facto semantics are.

One of the ways in which JSON syntax is not a subset of ECMAScript
syntax, is its definition of numbers. JSON numbers are effectively
arbitrary-precision decimals: if you change a JSON number in a given
document at any decimal place, then you are changing the meaning of
the document, even if the number would round to the same IEEE double
value.

The fact that some language bindings may (with specified options)
implicitly round numbers to the language's IEEE double type when
parsing a JSON document, does not contradict this. In doing so, the
binding is giving an approximation of the meaning of the document.
That approximation might be good enough for a particular use of JSON;
if it isn't, then the application programmer should use a different
binding, or different options to the binding.

None of this dictates a specific answer to what 'typeof aDecimal'
should return, but it needs to be clarified lest we do violence to
JSON's intended semantics by making incorrect assumptions about it.

-- 
David-Sarah Hopwood


More information about the Es-discuss mailing list