diff --git a/bson/bson_test.go b/bson/bson_test.go index 4a3465e478..b783c5cddb 100644 --- a/bson/bson_test.go +++ b/bson/bson_test.go @@ -584,11 +584,20 @@ func TestMapCodec(t *testing.T) { } func TestExtJSONEscapeKey(t *testing.T) { - doc := D{{Key: "\\usb#", Value: int32(1)}} + doc := D{ + { + Key: "\\usb#", + Value: int32(1), + }, + { + Key: "regex", + Value: Regex{Pattern: "ab\\\\\\\"ab", Options: "\""}, + }, + } b, err := MarshalExtJSON(&doc, false, false) noerr(t, err) - want := "{\"\\\\usb#\":1}" + want := `{"\\usb#":1,"regex":{"$regularExpression":{"pattern":"ab\\\\\\\"ab","options":"\""}}}` if diff := cmp.Diff(want, string(b)); diff != "" { t.Errorf("Marshaled documents do not match. got %v, want %v", string(b), want) } diff --git a/bson/extjson_writer.go b/bson/extjson_writer.go index 5f231ba1c7..2d43943fa7 100644 --- a/bson/extjson_writer.go +++ b/bson/extjson_writer.go @@ -407,12 +407,13 @@ func (ejvw *extJSONValueWriter) WriteRegex(pattern string, options string) error return err } + options = sortStringAlphebeticAscending(options) var buf bytes.Buffer buf.WriteString(`{"$regularExpression":{"pattern":`) writeStringWithEscapes(pattern, &buf, ejvw.escapeHTML) - buf.WriteString(`,"options":"`) - buf.WriteString(sortStringAlphebeticAscending(options)) - buf.WriteString(`"}},`) + buf.WriteString(`,"options":`) + writeStringWithEscapes(options, &buf, ejvw.escapeHTML) + buf.WriteString(`}},`) ejvw.buf = append(ejvw.buf, buf.Bytes()...)