Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Don't add undefined values to objects when parsing JSON #2127

Merged
merged 2 commits into from
Jan 18, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/happy-pets-breathe.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@khanacademy/perseus": minor
---

Avoid adding undefined values to objects parsed from Perseus JSON when properties are missing.
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import {assertFailure, success} from "../result";
import {assertFailure, assertSuccess, success} from "../result";

import {array} from "./array";
import {defaulted} from "./defaulted";
import {number} from "./number";
import {object} from "./object";
import {optional} from "./optional";
import {string} from "./string";
import {anyFailure, ctx, parseFailureWith} from "./test-helpers";

Expand Down Expand Up @@ -93,4 +94,19 @@ describe("object", () => {

expect(Train({}, ctx())).toEqual(success({boxcars: []}));
});

it("does not include fields not present on the original object", () => {
const Penguin = object({hat: optional(string)});
const result = Penguin({}, ctx());
assertSuccess(result);
expect(result.value).not.toHaveProperty("hat");
});

it("includes `undefined` fields from the original object", () => {
const Penguin = object({hat: optional(string)});
const result = Penguin({hat: undefined}, ctx());
assertSuccess(result);
expect(result.value).toHaveProperty("hat");
expect(result.value.hat).toBe(undefined);
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,9 @@ export function object<S extends ObjectSchema>(
for (const [prop, propParser] of Object.entries(schema)) {
const result = propParser(rawValue[prop], ctx.forSubtree(prop));
if (isSuccess(result)) {
ret[prop] = result.value;
if (result.value !== undefined || prop in rawValue) {
ret[prop] = result.value;
}
} else {
mismatches.push(...result.detail);
}
Expand Down
Loading
Loading