jsonpatch

package
v0.0.0-...-0cf3de4 Latest Latest
Warning

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

Go to latest
Published: Apr 9, 2016 License: Apache-2.0, MIT Imports: 4 Imported by: 0

README

jsonpatch

As per http://jsonpatch.com/ JSON Patch is specified in RFC 6902 from the IETF.

JSON Patch allows you to generate JSON that describes changes you want to make to a document, so you don't have to send the whole doc. JSON Patch format is supported by HTTP PATCH method, allowing for standards based partial updates via REST APIs.

go get github.com/mattbaird/jsonpatch

I tried some of the other "jsonpatch" go implementations, but none of them could diff two json documents and generate format like jsonpatch.com specifies. Here's an example of the patch format:

[
  { "op": "replace", "path": "/baz", "value": "boo" },
  { "op": "add", "path": "/hello", "value": ["world"] },
  { "op": "remove", "path": "/foo"}
]

The API is super simple #example

package main

import (
	"fmt"
	"github.com/mattbaird/jsonpatch"
)

var simpleA = `{"a":100, "b":200, "c":"hello"}`
var simpleB = `{"a":100, "b":200, "c":"goodbye"}`

func main() {
	patch, e := jsonpatch.CreatePatch([]byte(simpleA), []byte(simpleA))
	if e != nil {
		fmt.Printf("Error creating JSON patch:%v", e)
		return
	}
	for _, operation := range patch {
		fmt.Printf("%s\n", operation.Json())
	}
}

This code needs more tests, as it's a highly recursive, type-fiddly monster. It's not a lot of code, but it has to deal with a lot of complexity.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type ByPath

type ByPath []JsonPatchOperation

func (ByPath) Len

func (a ByPath) Len() int

func (ByPath) Less

func (a ByPath) Less(i, j int) bool

func (ByPath) Swap

func (a ByPath) Swap(i, j int)

type JsonPatchOperation

type JsonPatchOperation struct {
	Operation string      `json:"op"`
	Path      string      `json:"path"`
	Value     interface{} `json:"value,omitempty"`
}

func CreatePatch

func CreatePatch(a, b []byte) ([]JsonPatchOperation, error)

CreatePatch creates a patch as specified in http://jsonpatch.com/

'a' is original, 'b' is the modified document. Both are to be given as json encoded content. The function will return an array of JsonPatchOperations

An error will be returned if any of the two documents are invalid.

func NewPatch

func NewPatch(operation, path string, value interface{}) JsonPatchOperation

func (*JsonPatchOperation) Json

func (j *JsonPatchOperation) Json() string

Jump to

Keyboard shortcuts

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