mirkokiefer / canonical-json

Canonical JSON implementation - a repeatable version of JSON.stringify

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Bugs in "String" serialization

cyberphone opened this issue · comments

index.js serializes 0x7f as \u007f. This incompatible with ECMAScript 2015 and forward.
index2.js doesn't properly sort a property expressed as "".

I'm BTW working on the same problem and this is what I came up with:
https://github.com/cyberphone/json-canonicalization

Thanks for raising that @cyberphone , would be great if you could reproduce that in a failing test or even contribute a PR with a fix.

Hi @mirkokiefer Actually it is Crockford's json2 that is incompatible with ECMAScript 2015.
Index2 is almost right but fails on the "" edge case because ECMAScript 2015 has its own sorting rule.

This code does (AFAICT...) canonicalization in a way that is compatible with ECMAScript 2015 edition 6:

// ES6 JSON Canonicalizer
'use strict';
var canonicalize = function(object) {

    var buffer = '';
    serialize(object);
    return buffer;

    function serialize(object) {
        if (object !== null && typeof object === 'object') {
            if (Array.isArray(object)) {
                buffer += '[';
                let next = false;
                object.forEach((element) => {
                    if (next) {
                        buffer += ',';
                    }
                    next = true;
                    serialize(element);
                });
                buffer += ']';
            } else {
                buffer += '{';
                let next = false;
                Object.keys(object).sort().forEach((property) => {
                    if (next) {
                        buffer += ',';
                    }
                    next = true;
                    buffer += JSON.stringify(property);
                    buffer += ':';
                    serialize(object[property]);
                });
                buffer += '}';
            }
        } else {
            buffer += JSON.stringify(object);
        }
    }
};

module.exports = canonicalize;

I'm hoping to make this an IETF standard.