Skip to content

Commit

Permalink
{feature} support toJSON function
Browse files Browse the repository at this point in the history
  • Loading branch information
bgotink committed Sep 9, 2022
1 parent f0de4c1 commit aae8043
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 1 deletion.
2 changes: 1 addition & 1 deletion src/json.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -308,4 +308,4 @@ export function parse(text: string, reviver: JiKReviver<unknown>): unknown;
* @param value The JSON value to encode
* @throws If the given JSON value contains cycles.
*/
export function stringify(value: JsonValue): string;
export function stringify(value: unknown): string;
8 changes: 8 additions & 0 deletions src/json.js
Original file line number Diff line number Diff line change
Expand Up @@ -234,6 +234,14 @@ function fromJsonValue(
},
parents,
) {
if (
value != null &&
typeof value === 'object' &&
typeof (/** @type {{toJSON: Function}} */ (value).toJSON) === 'function'
) {
value = /** @type {{toJSON: Function}} */ (value).toJSON();
}

if (isLiteral(value)) {
const node = Node.create(nodeName);
node.addArgument(value ?? null);
Expand Down
12 changes: 12 additions & 0 deletions test/jik.js
Original file line number Diff line number Diff line change
Expand Up @@ -230,4 +230,16 @@ test('parse reviver', () => {
]);
});

test('stringify supports toJSON methods', () => {
expect(stringify(new Date('2022-09-09T10:23:23.445Z'))).toBe(
'- "2022-09-09T10:23:23.445Z"\n',
);

expect(
stringify({
toJSON: () => ['an', 'array'],
}),
).toBe('- "an" "array"\n');
});

test.run();

0 comments on commit aae8043

Please sign in to comment.