Skip to content

Commit c616a48

Browse files
committed
Fix marshaling invalid chars
Signed-off-by: John Howard <[email protected]>
1 parent 2c05a51 commit c616a48

File tree

2 files changed

+27
-15
lines changed

2 files changed

+27
-15
lines changed

v2/jsonpatch.go

Lines changed: 21 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
package jsonpatch
22

33
import (
4-
"bytes"
54
"encoding/json"
65
"fmt"
76
"reflect"
@@ -24,21 +23,28 @@ func (j *Operation) Json() string {
2423
}
2524

2625
func (j *Operation) MarshalJSON() ([]byte, error) {
27-
var b bytes.Buffer
28-
b.WriteString("{")
29-
b.WriteString(fmt.Sprintf(`"op":"%s"`, j.Operation))
30-
b.WriteString(fmt.Sprintf(`,"path":"%s"`, j.Path))
31-
// Consider omitting Value for non-nullable operations.
32-
if j.Value != nil || j.Operation == "replace" || j.Operation == "add" {
33-
v, err := json.Marshal(j.Value)
34-
if err != nil {
35-
return nil, err
36-
}
37-
b.WriteString(`,"value":`)
38-
b.Write(v)
26+
// Ensure for add and replace we emit `value: null`
27+
if j.Value == nil && (j.Operation == "replace" || j.Operation == "add") {
28+
return json.Marshal(struct {
29+
Operation string `json:"op"`
30+
Path string `json:"path"`
31+
Value interface{} `json:"value"`
32+
}{
33+
Operation: j.Operation,
34+
Path: j.Path,
35+
})
3936
}
40-
b.WriteString("}")
41-
return b.Bytes(), nil
37+
// otherwise just marshal normally. We cannot literally do json.Marshal(j) as it would be recursively
38+
// calling this function.
39+
return json.Marshal(struct {
40+
Operation string `json:"op"`
41+
Path string `json:"path"`
42+
Value interface{} `json:"value,omitempty"`
43+
}{
44+
Operation: j.Operation,
45+
Path: j.Path,
46+
Value: j.Value,
47+
})
4248
}
4349

4450
type ByPath []Operation

v2/jsonpatch_test.go

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -841,6 +841,10 @@ var (
841841
emptyKeyB = `{"":[]}`
842842
)
843843

844+
var (
845+
specialChars = string([]byte{123, 34, 92, 98, 34, 58, 91, 93, 125})
846+
)
847+
844848
func TestCreatePatch(t *testing.T) {
845849
cases := []struct {
846850
name string
@@ -888,6 +892,8 @@ func TestCreatePatch(t *testing.T) {
888892
{"Null Key uses replace operation", nullKeyA, nullKeyB},
889893
// empty key
890894
{"Empty key", emptyKeyA, emptyKeyB},
895+
// special chars
896+
{"Special chars", empty, specialChars},
891897
}
892898

893899
for _, c := range cases {

0 commit comments

Comments
 (0)