Skip to content

Date objects are destroyed by _deepClone via JSON.parse(JSON.stringify()) #332

Description

@monteiz

Date objects are destroyed by _deepClone via JSON.parse(JSON.stringify())

Description

The internal _deepClone method relies on JSON.parse(JSON.stringify(obj)) for object cloning. Because JSON.stringify automatically invokes Date.prototype.toJSON(), any Date instance in the source object is permanently cast into an ISO string during the cloning phase. This mutates the original data types in memory, breaking time zone calculations and native Date operations downstream.

Reproduction

const jsonpatch = require('fast-json-patch');

const document = {
  createdAt: new Date("2026-06-30T09:48:00Z")
};

const patch = [{ op: "add", path: "/updatedAt", value: new Date() }];

// _deepClone internally destroys the Date object
const result = jsonpatch.applyPatch(document, patch, false, false);

console.log(typeof result.newDocument.createdAt); 
// Expected: "object" (Date instance)
// Actual: "string"

Proposed Solution

I believe the core cloning mechanism should be updated to utilize the native structuredClone() algorithm, which is fully supported across Node.js 17+ and all modern browsers.

export function _deepClone(obj) {
    return structuredClone(obj);
}

This prevents silent data mutation while retaining performance. I can submit a PR with this update if the team agrees with this direction.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions