Skip to content
Open
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
21 changes: 14 additions & 7 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,26 +18,33 @@ export function isJSONSerializable(value: any): boolean {
if (value === undefined) {
return false;
}
if (value === null) {
return true;
}
const t = typeof value;
if (t === "string" || t === "number" || t === "boolean" || t === null) {
if (t === "string" || t === "number" || t === "boolean") {
return true;
}
if (t !== "object") {
return false; // bigint, function, symbol, undefined
return false; // bigint, function, symbol
}
if (Array.isArray(value)) {
return true;
}
if (value.buffer) {
return false;
}
// `FormData` and `URLSearchParams` shouldn't have a `toJSON` method,
// but Bun adds it, which is non-standard.
if (value instanceof FormData || value instanceof URLSearchParams) {
if (
(typeof FormData !== "undefined" && value instanceof FormData) ||
(typeof URLSearchParams !== "undefined" && value instanceof URLSearchParams)
) {
return false;
}
if (value.buffer) {
return false;
}
return (
(value.constructor && value.constructor.name === "Object") ||
!value.constructor ||
value.constructor.name === "Object" ||
typeof value.toJSON === "function"
);
}
Expand Down
21 changes: 21 additions & 0 deletions test/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -525,3 +525,24 @@ describe("ofetch", () => {
});
});
});

describe("isJSONSerializable", () => {
it("handles primitives and null safely", async () => {
const { isJSONSerializable } = await import("../src/utils.ts");
// eslint-disable-next-line unicorn/no-null
expect(isJSONSerializable(null)).toBe(true);
expect(isJSONSerializable(undefined)).toBe(false);
expect(isJSONSerializable("hello")).toBe(true);
expect(isJSONSerializable(123)).toBe(true);
expect(isJSONSerializable(true)).toBe(true);
expect(isJSONSerializable(Symbol("test"))).toBe(false);
});

it("handles objects and special types", async () => {
const { isJSONSerializable } = await import("../src/utils.ts");
expect(isJSONSerializable({ foo: "bar" })).toBe(true);
expect(isJSONSerializable(Object.create(null))).toBe(true);
expect(isJSONSerializable(new FormData())).toBe(false);
expect(isJSONSerializable(new URLSearchParams())).toBe(false);
});
});