jsonmerge

package module
v0.2.24 Latest Latest
Warning

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

Go to latest
Published: Jul 12, 2026 License: MIT Imports: 7 Imported by: 2 modules, 1 package

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

JSON Merge Patch for Go

Go Module Go Reference

A small RFC 7386 JSON Merge Patch library for Go with explicit patch values and lossless typed results

Features

  • RFC 7386 semantics: Objects merge recursively, null deletes object members, non-object patches replace the target, and arrays replace as a whole
  • Explicit patches: Build a Patch with Parse for JSON text or NewPatch for Go values
  • Clear string semantics: Plain string is a JSON string scalar; use []byte or jsonmerge.JSON for encoded JSON text
  • Lossless results: Apply returns the requested Go type when the merged JSON value can be represented without loss
  • Shared JSON semantics: Diff and Apply share one normalized JSON value model across maps, structs, bytes, and JSON text
  • Stable patch encoding: Patch.MarshalJSON emits deterministic compact JSON and preserves encoded JSON number literals
  • Small API: Learn Patch, Parse, NewPatch, Apply, Diff, and MarshalJSON

Installation

go get github.com/kaptinlin/jsonmerge

Requires Go 1.26.4 or newer.

Quick Start

package main

import (
	"fmt"
	"log"

	"github.com/kaptinlin/jsonmerge"
)

func main() {
	target := map[string]any{"name": "John", "age": 30}

	patch, err := jsonmerge.NewPatch(map[string]any{
		"age":   31,
		"email": "john@example.com",
	})
	if err != nil {
		log.Fatal(err)
	}

	result, err := jsonmerge.Apply(target, patch)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println(result["name"])
	fmt.Println(result["age"])
	fmt.Println(result["email"])
}

Document Forms

Form Behavior
map[string]any Object document form
[]byte Encoded JSON text; malformed text returns ErrInvalidJSON
jsonmerge.JSON Encoded JSON text carried as a string
string JSON string scalar, never parsed as JSON text
Structs and typed Go values Converted through JSON, then projected back without loss
Scalars and nil Accepted when the result can be represented as the requested type

If the merged JSON value cannot be represented by the requested Go type, Apply returns ErrCannotRepresent.

Core Operations

API Description
Parse(data []byte) (Patch, error) Parse encoded JSON text as a merge patch
NewPatch(value any) (Patch, error) Convert a Go value into a merge patch
Apply[T any](target T, patch Patch) (T, error) Apply a patch and return T when projection is lossless
Diff(source, target any) (Patch, error) Build a patch when RFC 7386 can represent the change; otherwise return ErrCannotRepresentPatch
(Patch).MarshalJSON() ([]byte, error) Encode a patch for storage or transport

Struct Targets

Use sparse object patches for typed targets. Struct zero values are normal JSON values when you put the struct itself into NewPatch.

type User struct {
	Name  string `json:"name"`
	Email string `json:"email,omitempty"`
	Age   int    `json:"age"`
}

user := User{Name: "John", Email: "john@example.com", Age: 30}
patch, _ := jsonmerge.NewPatch(map[string]any{"name": "Jane"})

user, _ = jsonmerge.Apply(user, patch)
fmt.Println(user.Name)  // Jane
fmt.Println(user.Email) // john@example.com
fmt.Println(user.Age)   // 30

Projection is strict. If a patch adds a member that the struct cannot represent, Apply fails with ErrCannotRepresent instead of silently dropping data.

JSON Text

Use Parse for patch text and jsonmerge.JSON or []byte for document text.

doc := jsonmerge.JSON(`{"name":"John","age":30}`)
patch, _ := jsonmerge.Parse([]byte(`{"name":"Jane"}`))

doc, _ = jsonmerge.Apply(doc, patch)
fmt.Println(doc)

Malformed text, duplicate object names, and invalid UTF-8 fail when parsed as text. The same bytes inside a Go string are just a string scalar when passed to NewPatch. Encoded JSON number literals are preserved through Parse, Apply, and Patch.MarshalJSON; large integers are not rounded while carried as JSON text.

Error Handling

The package wraps failures with sentinel errors so callers can use errors.Is:

  • ErrInvalidJSON
  • ErrInvalidValue
  • ErrCannotRepresent
  • ErrCannotRepresentPatch

Examples

Run the example programs from the repository root:

go run ./examples/map-merge
go run ./examples/struct-merge
go run ./examples/json-string-merge
go run ./examples/json-bytes-merge

See examples/ for complete programs.

Performance

The public API is pure by default and does not mutate caller-owned maps. Run benchmarks on your hardware with:

task bench

Development

task test          # Run all tests with race detection
task lint          # Run golangci-lint and tidy checks
task verify        # Run deps, fmt, vet, lint, test, and vuln

For development guidelines, see AGENTS.md. For detailed package contracts, see SPECS/.

Contributing

Contributions are welcome. See CONTRIBUTING.md for contribution guidelines.

License

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

Documentation

Overview

Package jsonmerge implements RFC 7386 JSON Merge Patch for Go.

Patches are explicit Patch values. Plain Go strings are JSON string values; use []byte or JSON when carrying encoded JSON text.

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	// ErrInvalidJSON indicates encoded JSON text is malformed.
	ErrInvalidJSON = errors.New("invalid json")

	// ErrInvalidValue indicates a Go value cannot be represented as JSON.
	ErrInvalidValue = errors.New("invalid json value")

	// ErrCannotRepresent indicates a JSON result cannot be projected into the requested Go type.
	ErrCannotRepresent = errors.New("cannot represent json value as requested type")

	// ErrCannotRepresentPatch indicates no JSON Merge Patch can transform the source into the target.
	ErrCannotRepresentPatch = errors.New("cannot represent target as json merge patch")
)

Functions

func Apply added in v0.2.24

func Apply[T any](target T, patch Patch) (T, error)

Apply applies patch to target according to RFC 7386.

Example
package main

import (
	"fmt"
	"log"

	"github.com/kaptinlin/jsonmerge"
)

func main() {
	type User struct {
		Name string `json:"name"`
		Age  int    `json:"age"`
	}

	user := User{Name: "John", Age: 30}
	patch, err := jsonmerge.NewPatch(map[string]any{"name": "Jane"})
	if err != nil {
		log.Fatal(err)
	}

	user, err = jsonmerge.Apply(user, patch)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println(user.Name)
	fmt.Println(user.Age)
}
Output:
Jane
30
Example (JsonText)
package main

import (
	"fmt"
	"log"

	"github.com/kaptinlin/jsonmerge"
)

func main() {
	doc := jsonmerge.JSON(`{"name":"John"}`)
	patch, err := jsonmerge.Parse([]byte(`{"name":"Jane"}`))
	if err != nil {
		log.Fatal(err)
	}

	doc, err = jsonmerge.Apply(doc, patch)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println(doc)
}
Output:
{"name":"Jane"}

Types

type JSON added in v0.2.24

type JSON string

JSON is a JSON text document carried as a string.

type Patch added in v0.2.24

type Patch struct {
	// contains filtered or unexported fields
}

Patch is an immutable JSON Merge Patch value.

func Diff added in v0.2.24

func Diff(source, target any) (Patch, error)

Diff returns a merge patch that transforms source into target when RFC 7386 can represent the change. It returns ErrCannotRepresentPatch when the target requires creating or replacing an object member with null.

Example
package main

import (
	"fmt"
	"log"

	"github.com/kaptinlin/jsonmerge"
)

func main() {
	before := map[string]any{"name": "John", "age": 30}
	after := map[string]any{"name": "Jane", "age": 30}

	patch, err := jsonmerge.Diff(before, after)
	if err != nil {
		log.Fatal(err)
	}

	data, err := patch.MarshalJSON()
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println(string(data))
}
Output:
{"name":"Jane"}

func NewPatch added in v0.2.24

func NewPatch(value any) (Patch, error)

NewPatch converts value into a merge patch.

Example
package main

import (
	"fmt"
	"log"

	"github.com/kaptinlin/jsonmerge"
)

func main() {
	patch, err := jsonmerge.NewPatch("raw string")
	if err != nil {
		log.Fatal(err)
	}

	doc, err := jsonmerge.Apply("draft", patch)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println(doc)
}
Output:
raw string

func Parse added in v0.2.24

func Parse(data []byte) (Patch, error)

Parse parses encoded JSON text as a merge patch.

func (Patch) MarshalJSON added in v0.2.24

func (p Patch) MarshalJSON() ([]byte, error)

MarshalJSON returns the JSON encoding of p.

Directories

Path Synopsis
examples
json-bytes-merge command
Package main demonstrates byte-slice JSON Merge Patch usage.
Package main demonstrates byte-slice JSON Merge Patch usage.
json-string-merge command
Package main demonstrates explicit JSON text and string scalar usage.
Package main demonstrates explicit JSON text and string scalar usage.
map-merge command
Package main demonstrates map-based JSON Merge Patch usage.
Package main demonstrates map-based JSON Merge Patch usage.
struct-merge command
Package main demonstrates struct-based JSON Merge Patch usage.
Package main demonstrates struct-based JSON Merge Patch usage.

Jump to

Keyboard shortcuts

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