jsonpatch

package module
v0.6.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 14, 2026 License: MIT Imports: 11 Imported by: 0

README

JSON Patch Go

A comprehensive Go implementation of JSON Patch (RFC 6902), JSON Predicate, and extended operations for JSON document manipulation with full type safety and generic support.

json-joy Compatible: This is a Go port of json-joy/json-patch with 95%+ behavioral compatibility, bringing all JSON Patch extended operations to the Go ecosystem with modern Go generics.

Go Reference Go Report Card

Quick Start

Installation
go get github.com/kaptinlin/jsonpatch
Basic Usage
package main

import (
    "encoding/json"
    "fmt"
    "log"

    "github.com/kaptinlin/jsonpatch"
)

func main() {
    // Original document
    doc := map[string]any{
        "name": "John",
        "age":  30,
    }

    // Create patch operations using struct syntax
    patch := []jsonpatch.Operation{
        {Op: "replace", Path: "/name", Value: "Jane"},
        {Op: "add", Path: "/email", Value: "jane@example.com"},
    }

    // Apply patch with type-safe generic API
    result, err := jsonpatch.ApplyPatch(doc, patch)
    if err != nil {
        log.Fatalf("Failed to apply patch: %v", err)
    }

    // result.Doc is automatically typed as map[string]any
    fmt.Printf("Name: %s\n", result.Doc["name"])
    fmt.Printf("Email: %s\n", result.Doc["email"])

    output, _ := json.MarshalIndent(result.Doc, "", "  ")
    fmt.Println(string(output))
    // Output:
    // {
    //   "age": 30,
    //   "email": "jane@example.com",
    //   "name": "Jane"
    // }
}
Type-Safe Struct Usage
type User struct {
    Name  string `json:"name"`
    Email string `json:"email,omitempty"`
    Age   int    `json:"age"`
}

func main() {
    user := User{Name: "John", Age: 30}

    patch := []jsonpatch.Operation{
        {Op: "replace", Path: "/name", Value: "Jane"},
        {Op: "add", Path: "/email", Value: "jane@example.com"},
    }

    // Type-safe: result.Doc is automatically typed as User
    result, err := jsonpatch.ApplyPatch(user, patch)
    if err != nil {
        log.Fatal(err)
    }

    fmt.Printf("Updated user: %+v\n", result.Doc)
    // Output: Updated user: {Name:Jane Email:jane@example.com Age:30}
}

Features

Type-Safe Generic API
  • Full Generic Support - No interface{} or type assertions needed
  • Compile-Time Type Safety - Catch type errors at compile time
  • Automatic Type Inference - Result types match input types
  • Multiple Document Types - map[string]any, structs, []byte, string
RFC 6902 Standard Operations (docs)
Operation Description
add Add new values to objects or arrays
remove Remove existing values
replace Replace existing values
move Move values to different locations
copy Copy values to new locations
test Test values for conditional operations
JSON Predicate Operations (docs)
Operation Description
contains Check string/array containment
defined / undefined Test path existence
starts / ends Test string prefix/suffix
in Check membership in arrays
less / more Numeric comparisons
matches Regular expression matching
type / test_type Type validation
test_string Position-based string testing
test_string_len String length validation
and / or / not Logical predicate combinations
Extended Operations (docs)
Operation Description
str_ins String insertion at position
str_del String deletion by position/substring
inc Increment/decrement numeric values
flip Toggle boolean values
split Split values at position
merge Merge adjacent array elements
extend Extend objects with properties
Codecs

Three codec formats for different use cases:

Codec Package Description
JSON codec/json Standard RFC 6902 JSON format
Compact codec/compact Array-based format with ~35% space savings
Binary codec/binary MessagePack binary format for maximum efficiency

json-joy Compatibility

This implementation provides 95%+ behavioral compatibility with the TypeScript json-joy/json-patch reference implementation.

Predicate Negation Pattern
// Direct negation (only test, test_string, test_string_len)
{Op: "test", Path: "/value", Value: 42, Not: true}
{Op: "test_string", Path: "/name", Pos: 0, Str: "test", Not: true}
{Op: "test_string_len", Path: "/name", Len: 5, Not: true}

// Second-order predicate negation (for all other predicates)
{
    Op:   "not",
    Path: "",
    Apply: []jsonpatch.Operation{
        {Op: "starts", Path: "/name", Value: "John"},
    },
}
Complex Predicate Logic
// Logical AND - all conditions must pass
{
    Op:   "and",
    Path: "",
    Apply: []jsonpatch.Operation{
        {Op: "starts", Path: "/name", Value: "John"},
        {Op: "ends", Path: "/name", Value: "Doe"},
    },
}

// Logical OR - any condition can pass
{
    Op:   "or",
    Path: "",
    Apply: []jsonpatch.Operation{
        {Op: "contains", Path: "/email", Value: "@gmail.com"},
        {Op: "contains", Path: "/email", Value: "@yahoo.com"},
    },
}

API Reference

Core Functions
// Apply a JSON Patch document to any supported document type
func ApplyPatch[T Document](doc T, patch []Operation, opts ...Option) (*PatchResult[T], error)

// Apply a single operation
func ApplyOp[T Document](doc T, operation Op, opts ...Option) (*OpResult[T], error)

// Apply multiple operations
func ApplyOps[T Document](doc T, operations []Op, opts ...Option) (*PatchResult[T], error)
Validation Functions
// Validate an array of operations
func ValidateOperations(ops []Operation, allowMatchesOp bool) error

// Validate a single operation
func ValidateOperation(operation Operation, allowMatchesOp bool) error
Functional Options
// Configure mutation behavior (default: false, creates deep copy)
jsonpatch.WithMutate(true)

// Configure custom regex matcher for "matches" operations
jsonpatch.WithMatcher(func(pattern string, ignoreCase bool) jsonpatch.RegexMatcher {
    // return custom matcher
})
Result Types
// Result of a single operation
type OpResult[T Document] struct {
    Doc T   // Result document with preserved type
    Old any // Previous value at the path
}

// Result of applying a patch
type PatchResult[T Document] struct {
    Doc T             // Result document with preserved type
    Res []OpResult[T] // Results for each operation
}

Codec Usage

Compact Codec
import "github.com/kaptinlin/jsonpatch/codec/compact"

// Standard operations
ops := []jsonpatch.Operation{
    {Op: "add", Path: "/name", Value: "John"},
    {Op: "replace", Path: "/age", Value: 30},
    {Op: "remove", Path: "/temp"},
}

// Encode to compact JSON with numeric opcodes (~35% space savings)
compactData, err := compact.EncodeJSON(ops)
// Result: [[0,"/name","John"],[2,"/age",30],[1,"/temp"]]

// Decode back to operations
decoded, err := compact.DecodeJSON(compactData)

// Or use the encoder/decoder structs for more control
encoder := compact.NewEncoder(compact.WithStringOpcode(true))
encoded, err := encoder.EncodeSlice(ops)
Binary Codec
import "github.com/kaptinlin/jsonpatch/codec/binary"

ops := []jsonpatch.Operation{
    {Op: "add", Path: "/user/name", Value: "Alice"},
    {Op: "inc", Path: "/user/score", Inc: 100},
}

codec := binary.New()

// Encode to MessagePack binary (40-60% smaller than JSON)
data, err := codec.Encode(ops)

// Decode back
decoded, err := codec.Decode(data)

Common Patterns

Type-Safe Operations
type Config struct {
    Version int    `json:"version"`
    Status  string `json:"status"`
    Enabled bool   `json:"enabled"`
}

config := Config{Version: 1, Status: "active", Enabled: true}

patch := []jsonpatch.Operation{
    {Op: "inc", Path: "/version", Inc: 1},
    {Op: "replace", Path: "/status", Value: "updated"},
    {Op: "flip", Path: "/enabled"},
}

// result.Doc is automatically typed as Config
result, err := jsonpatch.ApplyPatch(config, patch)
Safe Updates with Test Operations
patch := []jsonpatch.Operation{
    {Op: "test", Path: "/version", Value: 1},
    {Op: "replace", Path: "/status", Value: "updated"},
    {Op: "inc", Path: "/version", Inc: 1},
}

result, err := jsonpatch.ApplyPatch(doc, patch)
Mutation Control
// Preserve original document (default)
result, err := jsonpatch.ApplyPatch(doc, patch)

// Mutate original document for performance
result, err := jsonpatch.ApplyPatch(doc, patch, jsonpatch.WithMutate(true))
Batch Operations
var patch []jsonpatch.Operation

for i := range itemCount {
    patch = append(patch, jsonpatch.Operation{
        Op:    "replace",
        Path:  fmt.Sprintf("/items/%d/status", i),
        Value: "processed",
    })
}

result, err := jsonpatch.ApplyPatch(doc, patch)
Array Manipulation
patch := []jsonpatch.Operation{
    {Op: "add", Path: "/users/-", Value: map[string]any{"name": "New User"}},
    {Op: "add", Path: "/tags/0", Value: "important"},
    {Op: "remove", Path: "/items/2"},
}

result, err := jsonpatch.ApplyPatch(doc, patch)
String Operations
patch := []jsonpatch.Operation{
    {Op: "str_ins", Path: "/content", Pos: 0, Str: "Prefix: "},
    {Op: "str_del", Path: "/content", Pos: 6, Len: 10},
}

result, err := jsonpatch.ApplyPatch(doc, patch)
Error Handling
import "errors"

result, err := jsonpatch.ApplyPatch(doc, patch)
if err != nil {
    log.Printf("Patch application failed: %v", err)
    return err
}
Compact Codec for Storage/Network
import "github.com/kaptinlin/jsonpatch/codec/compact"

func storeOperations(ops []jsonpatch.Operation) error {
    compactData, err := compact.EncodeJSON(ops)
    if err != nil {
        return err
    }
    return database.Store(compactData)
}

Examples

Explore comprehensive examples in the examples/ directory (see examples/README.md for the complete guide):

Core Operations: Basic Operations | Array Operations | Conditional Operations | Copy & Move | String Operations | Extended Operations

Document Types: Struct Patch | Map Patch | JSON Bytes | JSON String

Codecs: Compact Codec | Binary Codec

Advanced: Batch Updates | Error Handling | Mutate Option

# Run any example
cd examples/<example-name> && go run main.go

Contributing

We welcome contributions! Please see CONTRIBUTING.md for guidelines.

Credits

This project is a Go port of json-joy/json-patch. Thanks to the original authors for their excellent work.

Original project: streamich/json-joy

License

This project is licensed under the MIT License. See LICENSE file for details.

Documentation

Overview

Package jsonpatch provides comprehensive JSON Patch operations with generic type support.

Implements JSON mutation operations including:

Core API Functions:

  • ApplyOp: Apply a single operation
  • ApplyOps: Apply multiple operations
  • ApplyPatch: Apply a JSON Patch to a document (main generic API)
  • ValidateOperations: Validate an array of operations
  • ValidateOperation: Validate a single operation

Basic usage:

doc := map[string]any{"name": "John", "age": 30}
patch := []Operation{
	{"op": "replace", "path": "/name", "value": "Jane"},
	{"op": "add", "path": "/email", "value": "jane@example.com"},
}
result, err := ApplyPatch(doc, patch, WithMutate(false))

The library provides type-safe operations for any supported document type.

Example
package main

import (
	"fmt"

	"github.com/go-json-experiment/json"
	"github.com/go-json-experiment/json/jsontext"
	"github.com/kaptinlin/jsonpatch"
)

func main() {
	// Original document
	doc := map[string]any{
		"user": map[string]any{
			"name":  "Alice",
			"email": "alice@example.com",
			"age":   25,
		},
		"settings": map[string]any{
			"theme": "dark",
		},
	}

	// Create patch operations
	patch := []jsonpatch.Operation{
		// Add a new field
		{
			Op:    "add",
			Path:  "/user/active",
			Value: true,
		},
		// Update existing field
		{
			Op:    "replace",
			Path:  "/user/age",
			Value: 26,
		},
		// Add to settings
		{
			Op:    "add",
			Path:  "/settings/notifications",
			Value: true,
		},
	}

	// Apply patch
	result, err := jsonpatch.ApplyPatch(doc, patch)
	if err != nil {
		fmt.Printf("Error: %v\n", err)
		return
	}

	// Print result
	resultJSON, _ := json.Marshal(result.Doc, jsontext.Multiline(true), json.Deterministic(true))
	fmt.Println(string(resultJSON))

}
Output:

{
	"settings": {
		"notifications": true,
		"theme": "dark"
	},
	"user": {
		"active": true,
		"age": 26,
		"email": "alice@example.com",
		"name": "Alice"
	}
}

Index

Examples

Constants

View Source
const (
	// JSON Patch (RFC 6902) operations
	OpAddType     = internal.OpAddType
	OpRemoveType  = internal.OpRemoveType
	OpReplaceType = internal.OpReplaceType
	OpMoveType    = internal.OpMoveType
	OpCopyType    = internal.OpCopyType
	OpTestType    = internal.OpTestType

	// JSON Predicate operations
	OpContainsType      = internal.OpContainsType
	OpDefinedType       = internal.OpDefinedType
	OpUndefinedType     = internal.OpUndefinedType
	OpTypeType          = internal.OpTypeType
	OpTestTypeType      = internal.OpTestTypeType
	OpTestStringType    = internal.OpTestStringType
	OpTestStringLenType = internal.OpTestStringLenType
	OpEndsType          = internal.OpEndsType
	OpStartsType        = internal.OpStartsType
	OpInType            = internal.OpInType
	OpLessType          = internal.OpLessType
	OpMoreType          = internal.OpMoreType
	OpMatchesType       = internal.OpMatchesType

	// Composite operations
	OpAndType = internal.OpAndType
	OpOrType  = internal.OpOrType
	OpNotType = internal.OpNotType

	// Extended operations
	OpFlipType   = internal.OpFlipType
	OpIncType    = internal.OpIncType
	OpStrInsType = internal.OpStrInsType
	OpStrDelType = internal.OpStrDelType
	OpSplitType  = internal.OpSplitType
	OpMergeType  = internal.OpMergeType
	OpExtendType = internal.OpExtendType
)

Operation type constants (string constants)

View Source
const (
	// JSON Patch (RFC 6902) operations
	OpAddCode     = internal.OpAddCode
	OpRemoveCode  = internal.OpRemoveCode
	OpReplaceCode = internal.OpReplaceCode
	OpCopyCode    = internal.OpCopyCode
	OpMoveCode    = internal.OpMoveCode
	OpTestCode    = internal.OpTestCode

	// String editing
	OpStrInsCode = internal.OpStrInsCode
	OpStrDelCode = internal.OpStrDelCode

	// Extra
	OpFlipCode = internal.OpFlipCode
	OpIncCode  = internal.OpIncCode

	// Slate.js
	OpSplitCode  = internal.OpSplitCode
	OpMergeCode  = internal.OpMergeCode
	OpExtendCode = internal.OpExtendCode

	// JSON Predicate
	OpContainsCode      = internal.OpContainsCode
	OpDefinedCode       = internal.OpDefinedCode
	OpEndsCode          = internal.OpEndsCode
	OpInCode            = internal.OpInCode
	OpLessCode          = internal.OpLessCode
	OpMatchesCode       = internal.OpMatchesCode
	OpMoreCode          = internal.OpMoreCode
	OpStartsCode        = internal.OpStartsCode
	OpUndefinedCode     = internal.OpUndefinedCode
	OpTestTypeCode      = internal.OpTestTypeCode
	OpTestStringCode    = internal.OpTestStringCode
	OpTestStringLenCode = internal.OpTestStringLenCode
	OpTypeCode          = internal.OpTypeCode
	OpAndCode           = internal.OpAndCode
	OpNotCode           = internal.OpNotCode
	OpOrCode            = internal.OpOrCode
)

Operation code constants (numeric constants)

View Source
const JSONPatchTypeArray = internal.JSONPatchTypeArray

JSONPatchTypeArray represents the JSON array type.

View Source
const JSONPatchTypeBoolean = internal.JSONPatchTypeBoolean

JSONPatchTypeBoolean represents the JSON boolean type.

View Source
const JSONPatchTypeInteger = internal.JSONPatchTypeInteger

JSONPatchTypeInteger represents the JSON integer type.

View Source
const JSONPatchTypeNull = internal.JSONPatchTypeNull

JSONPatchTypeNull represents the JSON null type.

View Source
const JSONPatchTypeNumber = internal.JSONPatchTypeNumber

JSONPatchTypeNumber represents the JSON number type.

View Source
const JSONPatchTypeObject = internal.JSONPatchTypeObject

JSONPatchTypeObject represents the JSON object type.

View Source
const JSONPatchTypeString = internal.JSONPatchTypeString

JSONPatchTypeString represents the JSON string type.

Variables

View Source
var (
	IsValidJSONPatchType = internal.IsValidJSONPatchType
	GetJSONPatchType     = internal.GetJSONPatchType

	// Operation type checking functions
	IsJSONPatchOperation            = internal.IsJSONPatchOperation
	IsPredicateOperation            = internal.IsPredicateOperation
	IsFirstOrderPredicateOperation  = internal.IsFirstOrderPredicateOperation
	IsSecondOrderPredicateOperation = internal.IsSecondOrderPredicateOperation
	IsJSONPatchExtendedOperation    = internal.IsJSONPatchExtendedOperation
)

Re-export functions

View Source
var (
	ErrNoOperationDecoded  = errors.New("no operation decoded")
	ErrInvalidDocumentType = errors.New("invalid document type")
	ErrConversionFailed    = errors.New("failed to convert result back to original type")
	ErrNoOperationResult   = errors.New("no operation result")
)

Operation application errors.

View Source
var (
	ErrNotArray             = errors.New("not an array")
	ErrEmptyPatch           = errors.New("empty operation patch")
	ErrInvalidOperation     = errors.New("invalid operation")
	ErrMissingPath          = errors.New("missing required field 'path'")
	ErrMissingOp            = errors.New("missing required field 'op'")
	ErrMissingValue         = errors.New("missing required field 'value'")
	ErrMissingFrom          = errors.New("missing required field 'from'")
	ErrInvalidPath          = errors.New("field 'path' must be a string")
	ErrInvalidOp            = errors.New("field 'op' must be a string")
	ErrInvalidFrom          = errors.New("field 'from' must be a string")
	ErrInvalidJSONPointer   = errors.New("invalid JSON pointer")
	ErrInvalidOldValue      = errors.New("invalid oldValue")
	ErrCannotMoveToChildren = errors.New("cannot move into own children")
	ErrInvalidIncValue      = errors.New("invalid inc value")
	ErrExpectedStringField  = errors.New("expected string field")
	ErrExpectedBooleanField = errors.New("expected field to be boolean")
	ErrExpectedIntegerField = errors.New("not an integer")
	ErrNegativeNumber       = errors.New("number is negative")
	ErrInvalidProps         = errors.New("invalid props field")
	ErrInvalidTypeField     = errors.New("invalid type field")
	ErrEmptyTypeList        = errors.New("empty type list")
	ErrInvalidType          = errors.New("invalid type")
	ErrValueMustBeString    = errors.New("value must be a string")
	ErrValueMustBeNumber    = errors.New("value must be a number")
	ErrValueMustBeArray     = errors.New("value must be an array")
	ErrValueTooLong         = errors.New("value too long")
	ErrInvalidNotModifier   = errors.New("invalid not modifier")
	ErrMatchesNotAllowed    = errors.New("matches operation not allowed")
	ErrMustBeArray          = errors.New("must be an array")
	ErrEmptyPredicateList   = errors.New("predicate list is empty")
	ErrPosGreaterThanZero   = errors.New("expected pos field to be greater than 0")

	// Additional static errors for err113 compliance
	ErrInOperationValueMustBeArray = errors.New("in operation value must be an array")
	ErrExpectedValueToBeString     = errors.New("expected value to be string")
	ErrExpectedIgnoreCaseBoolean   = errors.New("expected ignore_case to be boolean")
	ErrExpectedFieldString         = errors.New("expected field to be string")
)

Base validation errors - define clearly and concisely

View Source
var WithMatcher = internal.WithMatcher

WithMatcher configures a custom regex matcher for pattern operations.

View Source
var WithMutate = internal.WithMutate

WithMutate configures whether the patch operation should modify the original document.

Functions

func ApplyOp

func ApplyOp[T internal.Document](doc T, operation internal.Op, opts ...internal.Option) (*internal.OpResult[T], error)

ApplyOp applies a single operation to a document with generic type support. It automatically detects the document type and applies the appropriate strategy. Returns an OpResult containing the patched document and old value.

Example usage:

// Struct
user := User{Name: "John", Age: 30}
result, err := ApplyOp(user, operation, WithMutate(false))
if err == nil {
	patchedUser := result.Doc // Type: User
	oldValue := result.Old    // Previous value
}

// Map
doc := map[string]any{"name": "John", "age": 30}
result, err := ApplyOp(doc, operation, WithMutate(true))

The function preserves the input type: struct input returns struct output, map input returns map output, etc.

func ApplyOpDirect

func ApplyOpDirect(operation internal.Op, doc any) (internal.OpResult[any], error)

ApplyOpDirect applies an operation directly using the Op interface.

func ApplyOps

func ApplyOps[T internal.Document](doc T, operations []internal.Op, opts ...internal.Option) (*internal.PatchResult[T], error)

ApplyOps applies multiple operations to a document with generic type support. It automatically detects the document type and applies the appropriate strategy. Returns a PatchResult containing the patched document and operation results.

Example usage:

// Struct
user := User{Name: "John", Age: 30}
result, err := ApplyOps(user, operations, WithMutate(false))
if err == nil {
	patchedUser := result.Doc // Type: User
	opResults := result.Res   // Operation results
}

// Map
doc := map[string]any{"name": "John", "age": 30}
result, err := ApplyOps(doc, operations, WithMutate(true))

The function preserves the input type: struct input returns struct output, map input returns map output, etc.

func ApplyPatch

func ApplyPatch[T internal.Document](doc T, patch []internal.Operation, opts ...internal.Option) (*internal.PatchResult[T], error)

ApplyPatch applies a JSON Patch to any supported document type. It automatically detects the document type and applies the appropriate strategy. Returns a PatchResult containing the patched document and operation results.

Supported document types:

  • struct: Converted via JSON marshaling/unmarshaling
  • map[string]any: Applied directly using existing implementation
  • []byte: Parsed as JSON, patched, and re-encoded
  • string: Parsed as JSON string, patched, and re-encoded

Example usage:

// Struct
user := User{Name: "John", Age: 30}
result, err := ApplyPatch(user, patch)
if err == nil {
	patchedUser := result.Doc // Type: User
	operations := result.Res  // Operation results
}

// Map
doc := map[string]any{"name": "John", "age": 30}
result, err := ApplyPatch(doc, patch)
if err == nil {
	patchedDoc := result.Doc // Type: map[string]any
}

// JSON bytes
data := []byte(`{"name":"John","age":30}`)
result, err := ApplyPatch(data, patch)
if err == nil {
	patchedData := result.Doc // Type: []byte
}

The function preserves the input type: struct input returns struct output, map input returns map output, etc.

func DefaultOptions added in v0.2.0

func DefaultOptions() *internal.Options

DefaultOptions returns the default configuration for patch operations. By default, operations are immutable (documents are cloned before patching).

func GetOpCode

func GetOpCode(operation internal.Op) int

GetOpCode returns the operation code using the Op interface.

func GetOpPath

func GetOpPath(operation internal.Op) []string

GetOpPath returns the operation path using the Op interface.

func GetOpType

func GetOpType(operation internal.Op) internal.OpType

GetOpType returns the operation type using the Op interface.

func GetSecondOrderOps

func GetSecondOrderOps(predicate internal.SecondOrderPredicateOp) []internal.PredicateOp

GetSecondOrderOps returns sub-operations from a second-order predicate using the SecondOrderPredicateOp interface.

func IsNotPredicate

func IsNotPredicate(predicate internal.PredicateOp) bool

IsNotPredicate checks if a predicate is negated using the PredicateOp interface.

func TestPredicate

func TestPredicate(predicate internal.PredicateOp, doc any) (bool, error)

TestPredicate tests a predicate operation using the PredicateOp interface.

func ToCompact

func ToCompact(operation internal.Op) (internal.CompactOperation, error)

ToCompact converts an operation to compact format using the Op interface.

func ToJSON

func ToJSON(operation internal.Op) (internal.Operation, error)

ToJSON converts an operation to JSON format using the Op interface.

func ValidateOp

func ValidateOp(operation internal.Op) error

ValidateOp validates an operation using the Op interface.

func ValidateOperation

func ValidateOperation(operation Operation, allowMatchesOp bool) error

ValidateOperation validates a single JSON Patch operation.

func ValidateOperations

func ValidateOperations(ops []Operation, allowMatchesOp bool) error

ValidateOperations validates an array of JSON Patch operations.

Types

type CreateRegexMatcher

type CreateRegexMatcher = internal.CreateRegexMatcher

CreateRegexMatcher is a function type that creates a RegexMatcher from a pattern. This aligns with json-joy's CreateRegexMatcher type.

type Document added in v0.2.0

type Document = internal.Document

Document defines the supported document types for JSON Patch operations.

type Op

type Op = internal.Op

Op represents an executable operation.

type OpResult

type OpResult[T Document] = internal.OpResult[T]

OpResult represents the result of a single operation with generic type support.

type OpType

type OpType = internal.OpType

OpType represents the type of a JSON patch operation.

type Operation

type Operation = internal.Operation

Operation represents a JSON patch operation.

type Option added in v0.2.0

type Option = internal.Option

Option represents functional options for configuring patch operations.

type Options added in v0.2.0

type Options = internal.Options

Options holds configuration parameters for patch operations.

type PatchResult

type PatchResult[T Document] = internal.PatchResult[T]

PatchResult represents the result of applying a JSON Patch with generic type support.

type RegexMatcher

type RegexMatcher = internal.RegexMatcher

RegexMatcher is a function type that tests if a value matches a pattern. This aligns with json-joy's RegexMatcher type.

func CreateMatcherDefault

func CreateMatcherDefault(pattern string, ignoreCase bool) RegexMatcher

CreateMatcherDefault is the default regex matcher factory. It creates a RegexMatcher function from a pattern and ignoreCase flag. If the pattern is invalid, returns a matcher that always returns false. This aligns with json-joy's createMatcherDefault.

type Types added in v0.4.3

type Types = internal.JSONPatchType

Types represents the valid JSON types for type operations.

Directories

Path Synopsis
codec
binary
Package binary implements a MessagePack-based binary codec for JSON Patch operations.
Package binary implements a MessagePack-based binary codec for JSON Patch operations.
compact
Package compact implements a compact array-based codec for JSON Patch operations.
Package compact implements a compact array-based codec for JSON Patch operations.
json
Package json implements a codec for JSON Patch operations with full RFC 6902, JSON Predicate, and extended operation support.
Package json implements a codec for JSON Patch operations with full RFC 6902, JSON Predicate, and extended operation support.
json/tests
Package tests provides test data and automated codec tests for the JSON codec.
Package tests provides test data and automated codec tests for the JSON codec.
examples
array-operations command
Package main demonstrates array operations using JSON Patch.
Package main demonstrates array operations using JSON Patch.
basic command
Package main demonstrates basic JSON Patch operations.
Package main demonstrates basic JSON Patch operations.
basic-operations command
Package main demonstrates basic JSON Patch operations.
Package main demonstrates basic JSON Patch operations.
batch-update command
Package main demonstrates batch update operations using JSON Patch.
Package main demonstrates batch update operations using JSON Patch.
binary-codec command
Package main demonstrates binary codec operations using JSON Patch.
Package main demonstrates binary codec operations using JSON Patch.
compact-codec command
Package main demonstrates the compact codec functionality.
Package main demonstrates the compact codec functionality.
conditional-operations command
Package main demonstrates conditional operations using JSON Patch.
Package main demonstrates conditional operations using JSON Patch.
copy-move-operations command
Package main demonstrates copy and move operations using JSON Patch.
Package main demonstrates copy and move operations using JSON Patch.
error-handling command
Package main demonstrates error handling with JSON Patch operations.
Package main demonstrates error handling with JSON Patch operations.
errors command
Package main demonstrates error handling in JSON Patch operations.
Package main demonstrates error handling in JSON Patch operations.
extended command
Package main demonstrates extended JSON Patch operations.
Package main demonstrates extended JSON Patch operations.
json-bytes-patch command
Package main demonstrates JSON bytes patching operations.
Package main demonstrates JSON bytes patching operations.
json-string-patch command
Package main demonstrates JSON string patching operations.
Package main demonstrates JSON string patching operations.
map-patch command
Package main demonstrates map patching operations using JSON Patch.
Package main demonstrates map patching operations using JSON Patch.
mutate-option command
Package main demonstrates mutate option usage with JSON Patch.
Package main demonstrates mutate option usage with JSON Patch.
string-operations command
Package main demonstrates string operations using JSON Patch.
Package main demonstrates string operations using JSON Patch.
struct-patch command
Package main demonstrates struct patching operations using JSON Patch.
Package main demonstrates struct patching operations using JSON Patch.
types command
Package main demonstrates type operations with JSON Patch.
Package main demonstrates type operations with JSON Patch.
Package internal provides shared types, interfaces, and constants for JSON Patch operations.
Package internal provides shared types, interfaces, and constants for JSON Patch operations.
Package op provides implementations for JSON Patch operations.
Package op provides implementations for JSON Patch operations.
tests
data
Package data contains test case data and specifications for JSON Patch operations.
Package data contains test case data and specifications for JSON Patch operations.
testutils
Package testutils provides shared utilities for JSON Patch testing.
Package testutils provides shared utilities for JSON Patch testing.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL