JSON Duplicate Keys

Alexandre Morgaut Alexandre.Morgaut at 4d.com
Fri Jun 7 01:58:48 PDT 2013

On 6 juin 2013, at 13:42, Douglas Crockford wrote:

> The current RFC already says SHOULD. We don't have to weaken that. But
> we should be explicit about what a parser should do if it decides to
> accept away. The sentence
>     If a key is duplicated, a parser SHOULD reject.
> is not a change. It is implied by the first statement.  The thing that
> is a change is the third statement
>     If it does not reject, it MUST take only the last of the duplicated
> key pairs.


Still I would then, as throwing errors would also be Web breaking, add in the ECMAScript JSON API either:

1) an Array status property which may be called "lastParseErrors"

- it would be empty if there was no error
- it would be filled with Error instances if some error occurred

var obj = JSON.parse('{"myKey": "Value 1","myKey": 2}');
var errors = JSON.lastParsedErrors.length && JSON.lastParsedErrors;
if (errors) {
        // handle the errors

The Error message could in this case be:
-> The "myKeys" key is duplicated in this object: "$"
where "$" represent the root object as defined in JSONPath (http://goessner.net/articles/JsonPath/)
(if there was a "$" property in the root object, its path would be "$.$")
A JSONPath would in my opinion be much more usable than "line" + "column" or even more "index", as JSON is not initially meant to be multiline

ECMAScript might then define a Native "JSONError" or "ParseError" which instances would have the matching name property value

2) Instead of a "lastParseErrors", a "lastReport" property could available

The advantage would be that it could also handle warnings from the stringify() to alert the developer when some values were automatically dropped (like for undefined or function values), or replaced by null (like for Infinity or NaN values). The NativeError type might then be "StringifyError" or "CastError"
An alternative would be to consider those warnings as errors and expose either a generic "lastErrors" or an additional specific "lastStringifyErrors"

3) Another approach could be to let the parse() and stringify() methods accept an additional errorCallback parameter

It could be nice but it would force the developer to set values for the other optional parameters first even if he doesn't need them

I would have expected such Errors to be thrown as exceptions in strict mode but it's too late...

Alexandre Morgaut
Wakanda Community Manager

60, rue d'Alsace
92110 Clichy

Standard : +33 1 40 87 92 00
Email :    Alexandre.Morgaut at 4d.com
Web :      www.4D.com

More information about the es-discuss mailing list