jsonpatch

package module
v1.0.1 Latest Latest
Warning

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

Go to latest
Published: Jan 17, 2023 License: Apache-2.0 Imports: 4 Imported by: 0

README

go-json-patch-jsonpath

Build Status GoCover GoDoc

A Golang library implementing JSON Patch (rfc6902) with a digression to use path in JSONPath format (https://www.ietf.org/archive/id/draft-ietf-jsonpath-base-08.txt) instead of JSON Pointer (rfc6901).

Work in progress

This lib is a work in progress, for now only replace and remove operations has been implemented.

Installation

go get github.com/denouche/go-json-patch-jsonpath

Usage

package main

import (
	"fmt"
	jsonpatch "github.com/denouche/go-json-patch-jsonpath"
)

type People struct {
	Name    string    `json:"name"`
	Age     int       `json:"age"`
	Friends []*People `json:"friends"`
}

func NewPeople() *People {
	return &People{}
}

func main() {

	person := &People{
		Name: "Foo",
		Age:  42,
		Friends: []*People{
			{Name: "friend 1", Age: 19},
			{Name: "friend 2", Age: 25},
			{Name: "friend 3", Age: 42},
		},
	}

	r := jsonpatch.PatchRequests[People]{
		Patches: []*jsonpatch.PatchRequest[People]{
			{
				Operation: "replace",
				Path:      "$.name",
				Value:     "Bar",
			},
			{
				Operation: "remove",
				Path:      "$.friends[?(@.age < 20)]",
			},
		},
	}

	patchedPerson, err := r.Apply(person, NewPeople)
	if err != nil {
		fmt.Printf("error: %s\n", err)
	}

	fmt.Printf("name:%s age:%d friends:%d\n", person.Name, person.Age, len(person.Friends))
	// name:Foo age:42 friends:3

	fmt.Printf("name:%s age:%d friends:%d\n", patchedPerson.Name, patchedPerson.Age, len(patchedPerson.Friends))
	// name:Bar age:42 friends:2
}

References

JSON Patch: https://www.rfc-editor.org/rfc/rfc6902

JSONPath:

Documentation

Index

Constants

View Source
const (
	PatchOperationAdd     = "add"
	PatchOperationRemove  = "remove"
	PatchOperationReplace = "replace"
)

Variables

This section is empty.

Functions

This section is empty.

Types

type PatchOperation

type PatchOperation string

type PatchRequest

type PatchRequest[T any] struct {
	Operation PatchOperation `json:"op" validate:"required,oneof=remove replace"` // TODO implements add
	Path      string         `json:"path" validate:"required,jsonpath,ne=$"`
	Value     any            `json:"value"`
}

func (*PatchRequest[T]) Apply

func (pr *PatchRequest[T]) Apply(initialResource *T, emptyResource *T) (*T, error)

Apply TODO

type PatchRequests

type PatchRequests[T any] struct {
	Patches []*PatchRequest[T] `json:"patches" validate:"required,min=1,dive,required"`
}

func (*PatchRequests[T]) Apply

func (prs *PatchRequests[T]) Apply(initialResource *T, newer func() *T) (*T, error)

Apply TODO

Jump to

Keyboard shortcuts

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