Skip to content

JsonPatchDocument

Definition

Namespace: Corvus.Text.Json.Patch
Assembly: Corvus.Text.Json.dll

An RFC 6902 JSON Patch document.

public readonly struct JsonPatchDocument : IJsonElement<JsonPatchDocument>, IJsonElement, IReadOnlyCollection<JsonPatchDocument.PatchOperation>, IEnumerable<JsonPatchDocument.PatchOperation>, IEnumerable, IFormattable, ISpanFormattable, IUtf8SpanFormattable

Implements

IJsonElement<JsonPatchDocument>, IJsonElement, IReadOnlyCollection<JsonPatchDocument.PatchOperation>, IEnumerable<JsonPatchDocument.PatchOperation>, IEnumerable, IFormattable, ISpanFormattable, IUtf8SpanFormattable

Properties

Property Type Description
DefaultInstance static JsonPatchDocument Gets the default instance.
this[int] JsonPatchDocument.PatchOperation
Rank static int Gets the rank of the array.
ValueKind JsonValueKind

Methods

Method Description
Build static
Clone()
Create static
CreateBuilder static
EnumerateArray()
Equals
EvaluateSchema(IJsonSchemaResultsCollector?)
Freeze()
From(T) static
GetArrayLength()
GetEnumerator() Gets an enumerator over the items of the array, for foreach. It does not allocate.
GetHashCode()
ParseValue static
ToString
TryFormat
TryParseValue(Utf8JsonReader, Nullable<JsonPatchDocument>) static
WriteTo(Utf8JsonWriter)

Operators

Operator Description
Equality
Implicit Converts the instance to a JsonElement.
Inequality

Examples

A JsonPatchDocument represents an RFC 6902 JSON Patch — an array of operations that describe mutations to apply to a JSON document.

Parsing from JSON

using Corvus.Text.Json.Patch;

JsonPatchDocument patch = JsonPatchDocument.ParseValue(
    """
    [
        { "op": "replace", "path": "/name", "value": "Bob" },
        { "op": "add", "path": "/email", "value": "bob@example.com" },
        { "op": "remove", "path": "/temporary" }
    ]
    """u8);

Applying to a mutable document

Use TryValidateAndApplyPatch when the patch comes from an untrusted source — it validates the patch against its JSON Schema before applying:

using Corvus.Text.Json;
using Corvus.Text.Json.Patch;

using var parsedDoc = ParsedJsonDocument<JsonElement>.Parse(json);
using JsonWorkspace workspace = JsonWorkspace.Create();
using var builder = parsedDoc.RootElement.CreateBuilder(workspace);

JsonElement.Mutable root = builder.RootElement;

bool applied = root.TryValidateAndApplyPatch(patch);

Building a patch with PatchBuilder

For locally-constructed patches that don't need validation, use PatchBuilder:

JsonPatchDocument patch = root.BeginPatch(workspace)
    .Replace("/name"u8, "Charlie")
    .Add("/tags/-"u8, "admin")
    .Remove("/temp"u8)
    .GetPatchAndDispose();

root.TryApplyPatch(patch);

Applies To

Product Versions
.NET 9, 10
.NET Standard 2.0, 2.1

Collaborate with us on GitHub

The source for this content can be found on GitHub, where you can also create and review issues and pull requests.

Open an issue