Hyperlinkv0.8.0-beta.28

JsonPatch

JsonPatch.applyfunctioneffect/JsonPatch.ts:287
(patch: JsonPatch, oldValue: Schema.Json): Schema.Json

Applies a JSON Patch to a JSON document.

When to use

Use to execute patches generated by get, transform documents with manually constructed patches, or process patch operations from external sources.

Details

Executes patch operations sequentially, so later operations see changes made by earlier operations. It never mutates the input document; array and object operations copy the affected containers. An empty patch returns the original reference, and a root replace (path: "") returns the provided value directly.

Gotchas

Invalid paths, missing properties, and out-of-bounds array indices throw errors.

Example (Applying a patch)

import { JsonPatch } from "effect"

const document = { items: [1, 2, 3], total: 6 }
const patch: JsonPatch.JsonPatch = [
  { op: "add", path: "/items/-", value: 4 },
  { op: "replace", path: "/total", value: 10 }
]

const result = JsonPatch.apply(patch, document)
// { items: [1, 2, 3, 4], total: 10 }
export function apply(patch: JsonPatch, oldValue: Schema.Json): Schema.Json {
  let doc = oldValue

  for (const op of patch) {
    switch (op.op) {
      case "replace": {
        doc = op.path === "" ? op.value : setAt(doc, op.path, op.value, "replace")
        break
      }
      case "add": {
        doc = addAt(doc, op.path, op.value)
        break
      }
      case "remove": {
        doc = setAt(doc, op.path, undefined, "remove")
        break
      }
    }
  }

  return doc
}
Referenced by 1 symbols