From 7493c803f0efe11826f4de043948a9e843bd32e2 Mon Sep 17 00:00:00 2001 From: Suyog241005 Date: Sun, 24 May 2026 09:22:19 +0530 Subject: [PATCH] fix: avoid trailing comma in jsonStringify when replacer skips last property --- lib/common.js | 9 +++++---- lib/stringify.spec.ts | 14 ++++++++++++++ 2 files changed, 19 insertions(+), 4 deletions(-) diff --git a/lib/common.js b/lib/common.js index 28183cdf..bc517102 100644 --- a/lib/common.js +++ b/lib/common.js @@ -126,15 +126,16 @@ const stringifyObject = (value, replacer, space, pointer, depth) => { const colonSpacing = space ? " " : ""; let result = "{" + padding + space; - for (let index = 0; index < entries.length; index++) { - const [key, value] = entries[index]; + let first = true; + for (const [key, value] of entries) { const keyPointer = JsonPointer.append(key, pointer); const stringifiedValue = stringifyValue(value, replacer, space, key, keyPointer, depth + 1); if (stringifiedValue !== undefined) { - result += JSON.stringify(key) + ":" + colonSpacing + stringifiedValue; - if (entries[index + 1]) { + if (!first) { result += `,${padding}${space}`; } + first = false; + result += JSON.stringify(key) + ":" + colonSpacing + stringifiedValue; } } return result + padding + "}"; diff --git a/lib/stringify.spec.ts b/lib/stringify.spec.ts index b61c80fc..1566c09d 100644 --- a/lib/stringify.spec.ts +++ b/lib/stringify.spec.ts @@ -39,6 +39,20 @@ describe("Json.stringify", () => { expect(jsonStringify(value, replacer)).to.eql(JSON.stringify(value, replacer)); }); + it("should remove the last property when it returns undefined without leaving a trailing comma", () => { + const value = { + aaa: "foo", + bbb: "bar" + }; + const replacer = (key: string, value: unknown) => { + if (key !== "bbb") { + return value; + } + }; + + expect(jsonStringify(value, replacer)).to.eql(JSON.stringify(value, replacer)); + }); + it("should remove items that return undefined", () => { const value = ["foo", "bar"]; const replacer = (key: string, value: unknown) => {