Skip to content

Commit

Permalink
Fixes a bug where JSON object keys were not escaped
Browse files Browse the repository at this point in the history
  • Loading branch information
skmcgrail authored Aug 9, 2022
2 parents 3ea84eb + d2ccf6f commit bed880b
Show file tree
Hide file tree
Showing 4 changed files with 73 additions and 5 deletions.
8 changes: 8 additions & 0 deletions .changelog/461d165a25e346669f076407175b6bd5.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"id": "461d165a-25e3-4666-9f07-6407175b6bd5",
"type": "bugfix",
"description": "Fixes a bug where JSON object keys were not escaped.",
"modules": [
"."
]
}
49 changes: 49 additions & 0 deletions encoding/json/escape_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
package json

import (
"bytes"
"testing"
)

func TestEscapeStringBytes(t *testing.T) {
cases := map[string]struct {
expected string
input []byte
}{
"safeSet only": {
expected: `"mountainPotato"`,
input: []byte("mountainPotato"),
},
"parenthesis": {
expected: `"foo\""`,
input: []byte(`foo"`),
},
"double escape": {
expected: `"hello\\\\world"`,
input: []byte(`hello\\world`),
},
"new line": {
expected: `"foo\nbar"`,
input: []byte("foo\nbar"),
},
"carriage return": {
expected: `"foo\rbar"`,
input: []byte("foo\rbar"),
},
"tab": {
expected: `"foo\tbar"`,
input: []byte("foo\tbar"),
},
}
for name, c := range cases {
t.Run(name, func(t *testing.T) {
var buffer bytes.Buffer
escapeStringBytes(&buffer, c.input)
expected := c.expected
actual := buffer.String()
if expected != actual {
t.Errorf("\nexpected %v \nactual %v", expected, actual)
}
})
}
}
4 changes: 1 addition & 3 deletions encoding/json/object.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,7 @@ func newObject(w *bytes.Buffer, scratch *[]byte) *Object {
}

func (o *Object) writeKey(key string) {
o.w.WriteRune(quote)
o.w.Write([]byte(key))
o.w.WriteRune(quote)
escapeStringBytes(o.w, []byte(key))
o.w.WriteRune(colon)
}

Expand Down
17 changes: 15 additions & 2 deletions encoding/json/object_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,9 @@ import (

func TestObject(t *testing.T) {
buffer := bytes.NewBuffer(nil)
scatch := make([]byte, 64)
scratch := make([]byte, 64)

object := newObject(buffer, &scatch)
object := newObject(buffer, &scratch)
object.Key("foo").String("bar")
object.Key("faz").String("baz")
object.Close()
Expand All @@ -19,3 +19,16 @@ func TestObject(t *testing.T) {
t.Errorf("expected %+q, but got %+q", e, a)
}
}

func TestObjectKey_escaped(t *testing.T) {
jsonEncoder := NewEncoder()
object := jsonEncoder.Object()
object.Key("foo\"").String("bar")
object.Key("faz").String("baz")
object.Close()

e := []byte(`{"foo\"":"bar","faz":"baz"}`)
if a := object.w.Bytes(); bytes.Compare(e, a) != 0 {
t.Errorf("expected %+q, but got %+q", e, a)
}
}

0 comments on commit bed880b

Please sign in to comment.