Skip to content

Commit

Permalink
Fix marshaling invalid chars
Browse files Browse the repository at this point in the history
Signed-off-by: John Howard <howardjohn@google.com>
  • Loading branch information
howardjohn committed May 16, 2023
1 parent 2c05a51 commit c616a48
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 15 deletions.
36 changes: 21 additions & 15 deletions v2/jsonpatch.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package jsonpatch

import (
"bytes"
"encoding/json"
"fmt"
"reflect"
Expand All @@ -24,21 +23,28 @@ func (j *Operation) Json() string {
}

func (j *Operation) MarshalJSON() ([]byte, error) {
var b bytes.Buffer
b.WriteString("{")
b.WriteString(fmt.Sprintf(`"op":"%s"`, j.Operation))
b.WriteString(fmt.Sprintf(`,"path":"%s"`, j.Path))
// Consider omitting Value for non-nullable operations.
if j.Value != nil || j.Operation == "replace" || j.Operation == "add" {
v, err := json.Marshal(j.Value)
if err != nil {
return nil, err
}
b.WriteString(`,"value":`)
b.Write(v)
// Ensure for add and replace we emit `value: null`
if j.Value == nil && (j.Operation == "replace" || j.Operation == "add") {
return json.Marshal(struct {
Operation string `json:"op"`
Path string `json:"path"`
Value interface{} `json:"value"`
}{
Operation: j.Operation,
Path: j.Path,
})
}
b.WriteString("}")
return b.Bytes(), nil
// otherwise just marshal normally. We cannot literally do json.Marshal(j) as it would be recursively
// calling this function.
return json.Marshal(struct {
Operation string `json:"op"`
Path string `json:"path"`
Value interface{} `json:"value,omitempty"`
}{
Operation: j.Operation,
Path: j.Path,
Value: j.Value,
})
}

type ByPath []Operation
Expand Down
6 changes: 6 additions & 0 deletions v2/jsonpatch_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -841,6 +841,10 @@ var (
emptyKeyB = `{"":[]}`
)

var (
specialChars = string([]byte{123, 34, 92, 98, 34, 58, 91, 93, 125})
)

func TestCreatePatch(t *testing.T) {
cases := []struct {
name string
Expand Down Expand Up @@ -888,6 +892,8 @@ func TestCreatePatch(t *testing.T) {
{"Null Key uses replace operation", nullKeyA, nullKeyB},
// empty key
{"Empty key", emptyKeyA, emptyKeyB},
// special chars
{"Special chars", empty, specialChars},
}

for _, c := range cases {
Expand Down

0 comments on commit c616a48

Please sign in to comment.