JSON Patch is a format for describing updates to a JSON document as a list of operations.
For a quick overview, see jsonpatch.com.
It is often used when systems want to send incremental updates instead of resending a full object every time. For example, a server can stream small patches over SSE or WebSockets to update a client-side document, chat state, or tool result in place. This pattern also shows up in streaming AI chat UIs, where the server may send structured deltas as new content arrives.
In this question, implement applyJsonPatch(document, operations) which applies a list of patch operations to a nested object and returns the patched result.
This question is intentionally simplified:
add, remove, and replace operations need to be supported.document only contains plain objects and JSON primitive values. Arrays are out of scope.path uses /-delimited object keys such as /user/name.applyJsonPatch({user: {name: 'Alice',role: 'admin',},},[{ op: 'replace', path: '/user/name', value: 'Bob' },{ op: 'add', path: '/user/active', value: true },],);// {// user: {// name: 'Bob',// role: 'admin',// active: true,// },// }
applyJsonPatch({settings: {theme: 'dark',locale: 'en-US',},},[{ op: 'remove', path: '/settings/locale' }],);// {// settings: {// theme: 'dark',// },// }
applyJsonPatch(document, operations) accepts the following arguments:
| Argument | Type | Description |
|---|---|---|
document | Object | A nested object containing JSON primitive values or other plain objects. |
operations | Array | A list of patch operations to apply in order. |
Each operation has one of the following shapes:
{ op: 'add', path: string, value: unknown }{ op: 'remove', path: string }{ op: 'replace', path: string, value: unknown }
Returns a new object with all operations applied in order.
add creates or overwrites the final property at path.remove deletes the final property at path.replace overwrites the existing property at path.document or operations.console.log() 语句将显示在此处。