文档:https://pkg.go.dev/github.com/evanphx/json-patch

Func

  1. // CreateMergePatch 返回从 original 到 modified 需要做改动,也就是patch
  2. func CreateMergePatch(originalJSON, modifiedJSON []byte) ([]byte, error)
  3. // MergePatch 将docData 做 patch 改动
  4. func MergePatch(docData, patchData []byte) ([]byte, error)
  5. // Equal 比较两个json是否相等
  6. func Equal(a, b []byte) bool

type Patch

  1. type Patch []Operation
  2. func DecodePatch(buf []byte) (Patch, error)
  3. func (p Patch) Apply(doc []byte) ([]byte, error)

type Operation

  1. type Operation map[string]*json.RawMessage
  2. func (o Operation) From() (string, error)
  3. func (o Operation) Kind() string // reads the "op" field of the Operation
  4. func (o Operation) Path() (string, error) // reads the "path" field of the Operation
  5. func (o Operation) ValueInterface() (interface{}, error)

Demo

Combine merge patches

  1. func main() {
  2. original := []byte(`{"name": "John", "age": 24, "height": 3.21}`)
  3. target := []byte(`{"name": "Jane", "age": 24, "money":1}`)
  4. patch, err := jsonpatch.CreateMergePatch(original, target)
  5. if err != nil {
  6. panic(err)
  7. }
  8. fmt.Println(string(patch))
  9. // {"height":null,"money":1,"name":"Jane"}
  10. alternative := []byte(`{"name": "Tina", "age": 28, "height": 3.75}`)
  11. modifiedAlternative, err := jsonpatch.MergePatch(alternative, patch)
  12. fmt.Println(string(modifiedAlternative))
  13. // {"age":28,"money":1,"name":"Jane"}
  14. }

apply a merge patch

  1. func main() {
  2. patchJSON := []byte(`[
  3. {"op": "replace", "path": "/name", "value": "Jane"},
  4. {"op": "remove", "path": "/height"},
  5. {"op": "add", "path": "/money", "value": 100},
  6. {"op": "add", "path": "/obj/key", "value": "val"}
  7. ]`)
  8. original := []byte(`{"name": "John", "age": 24, "height": 3.21, "obj":{}}`)
  9. patch, err := jsonpatch.DecodePatch(patchJSON)
  10. if err != nil {
  11. panic(err)
  12. }
  13. modified, err := patch.Apply(original)
  14. if err != nil {
  15. panic(err)
  16. }
  17. fmt.Println(string(modified))
  18. // {"age":24,"money":100,"name":"Jane","obj":{"key":"val"}}
  19. }