Skip to content

Commit

Permalink
fixed bug with toJSON not being considdered
Browse files Browse the repository at this point in the history
  • Loading branch information
erdtman committed Nov 26, 2021
1 parent cc660c1 commit 5ccd0bb
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 10 deletions.
14 changes: 7 additions & 7 deletions examples/example.js
Expand Up @@ -5,17 +5,17 @@
JSON.canonicalize = require('../');

const json = {
'1': {'f': {'f': 'hi', 'F': 5}, '\n': 56.0},
'10': {},
1: { f: { f: 'hi', F: 5 }, '\n': 56.0 },
10: {},
'': 'empty',
'a': {},
'111': [
a: {},
111: [
{
'e': 'yes',
'E': 'no'
e: 'yes',
E: 'no'
}
],
'A': {}
A: {}
};

console.log(JSON.canonicalize(json));
9 changes: 6 additions & 3 deletions lib/canonicalize.js
Expand Up @@ -3,10 +3,14 @@
'use strict';

module.exports = function serialize (object) {
if (object === null || typeof object !== 'object' || object.toJSON != null) {
if (object === null || typeof object !== 'object') {
return JSON.stringify(object);
}

if (typeof object.toJSON === 'function') {
return serialize(object.toJSON());
}

if (Array.isArray(object)) {
return '[' + object.reduce((t, cv, ci) => {
const comma = ci === 0 ? '' : ',';
Expand All @@ -16,8 +20,7 @@ module.exports = function serialize (object) {
}

return '{' + Object.keys(object).sort().reduce((t, cv, ci) => {
if (object[cv] === undefined ||
typeof object[cv] === 'symbol') {
if (object[cv] === undefined || typeof object[cv] === 'symbol' || cv === 'toJSON') {
return t;
}
const comma = t.length === 0 ? '' : ',';
Expand Down
23 changes: 23 additions & 0 deletions test/simpletests.js
Expand Up @@ -33,6 +33,13 @@ test('null and undefined values in array', t => {
t.is(actual, expected);
});

test('object in array', t => {
const input = [{ b: 123, a: 'string' }];
const expected = '[{"a":"string","b":123}]';
const actual = JSON.canonicalize(input);
t.is(actual, expected);
});

test('empty object', t => {
const input = {};
const expected = '{}';
Expand Down Expand Up @@ -109,3 +116,19 @@ test('object with symbol key', t => {
const actual = JSON.canonicalize(input);
t.is(actual, expected);
});

test('object with toJSON', t => {
const input = {
a: 123,
b: 456,
toJSON: function () {
return {
b: this.b,
a: this.a
};
}
};
const expected = '{"a":123,"b":456}';
const actual = JSON.canonicalize(input);
t.is(actual, expected);
});

0 comments on commit 5ccd0bb

Please sign in to comment.