Skip to content

Commit 21d6004

Browse files
author
iwysiu
committed
GODRIVER-1456 make extJSONValueWriter escape keys (#270)
1 parent c255636 commit 21d6004

File tree

2 files changed

+22
-1
lines changed

2 files changed

+22
-1
lines changed

bson/bson_test.go

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -111,3 +111,21 @@ func TestD(t *testing.T) {
111111
}
112112
})
113113
}
114+
115+
func TestExtJSONEscapeKey(t *testing.T) {
116+
doc := D{{Key: "\\usb#", Value: int32(1)}}
117+
b, err := MarshalExtJSON(&doc, false, false)
118+
noerr(t, err)
119+
120+
want := "{\"\\\\usb#\":1}"
121+
if diff := cmp.Diff(want, string(b)); diff != "" {
122+
t.Errorf("Marshaled documents do not match. got %v, want %v", string(b), want)
123+
}
124+
125+
var got D
126+
err = UnmarshalExtJSON(b, false, &got)
127+
noerr(t, err)
128+
if !cmp.Equal(got, doc) {
129+
t.Errorf("Unmarshaled documents do not match. got %v; want %v", got, doc)
130+
}
131+
}

bson/bsonrw/extjson_writer.go

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -536,7 +536,10 @@ func (ejvw *extJSONValueWriter) WriteUndefined() error {
536536
func (ejvw *extJSONValueWriter) WriteDocumentElement(key string) (ValueWriter, error) {
537537
switch ejvw.stack[ejvw.frame].mode {
538538
case mDocument, mTopLevel, mCodeWithScope:
539-
ejvw.buf = append(ejvw.buf, []byte(fmt.Sprintf(`"%s":`, key))...)
539+
var buf bytes.Buffer
540+
writeStringWithEscapes(key, &buf, ejvw.escapeHTML)
541+
542+
ejvw.buf = append(ejvw.buf, []byte(fmt.Sprintf(`%s:`, buf.String()))...)
540543
ejvw.push(mElement)
541544
default:
542545
return nil, ejvw.invalidTransitionErr(mElement, "WriteDocumentElement", []mode{mDocument, mTopLevel, mCodeWithScope})

0 commit comments

Comments
 (0)