patterntypescriptexpressModerate
JSON Patch vs JSON Merge Patch for PATCH Endpoints
Viewed 0 times
JSON PatchJSON Merge PatchRFC 6902RFC 7396PATCHpartial update
Problem
PATCH endpoints are implemented inconsistently — some accept partial JSON, some accept operation arrays. Clients don't know how to send partial updates, and setting a field to null is ambiguous.
Solution
Choose between JSON Patch (RFC 6902) and JSON Merge Patch (RFC 7396) intentionally.
// JSON Merge Patch (simpler — send partial object)
// Content-Type: application/merge-patch+json
// Null = delete field, missing = unchanged
const patch = { name: 'Alice', nickname: null }; // sets name, deletes nickname
// JSON Patch (precise operations)
// Content-Type: application/json-patch+json
const patch = [
{ op: 'replace', path: '/name', value: 'Alice' },
{ op: 'add', path: '/tags/-', value: 'admin' },
{ op: 'remove', path: '/nickname' },
{ op: 'test', path: '/version', value: 3 }, // precondition check
];
// Express handler
import jsonpatch from 'fast-json-patch';
app.patch('/users/:id', async (req, res) => {
const user = await db.getUser(req.params.id);
const patched = jsonpatch.applyPatch(user, req.body).newDocument;
await db.updateUser(req.params.id, patched);
res.json(patched);
});Why
JSON Merge Patch is simple but cannot express array operations or distinguishing 'delete field' from 'set to null'. JSON Patch is more expressive but verbose. The choice depends on your data model.
Gotchas
- JSON Merge Patch cannot append to arrays — only replace the entire array.
- JSON Patch operations are atomic — all operations succeed or all fail.
- Always validate the patch against your schema before applying it.
Revisions (0)
No revisions yet.