Skip to content

Commit 0fc9e1d

Browse files
erhskriptble
authored andcommitted
Add ToExtJSON to bson.Document type
Co-authored-by: Eliot Horowitz <[email protected]> Co-authored-by: Kris Brandow <[email protected]> Change-Id: I746a2d6eff298700e9cee2579fad7b875b84d558
1 parent f826ab8 commit 0fc9e1d

File tree

2 files changed

+56
-0
lines changed

2 files changed

+56
-0
lines changed

bson/document.go

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -755,3 +755,28 @@ func (d *Document) String() string {
755755

756756
return buf.String()
757757
}
758+
759+
// ToExtJSON marshals this document to BSON and transforms that BSON to
760+
// extended JSON. If there is an error during the conversion, this method
761+
// will return an empty string. To receive the error, use the ToExtJSONErr
762+
// method.
763+
func (d *Document) ToExtJSON(canonical bool) string {
764+
s, err := d.ToExtJSONErr(canonical)
765+
if err != nil {
766+
return ""
767+
}
768+
return s
769+
}
770+
771+
// ToExtJSONErr marshals this document to BSON and transforms that BSON to
772+
// extended JSON.
773+
func (d *Document) ToExtJSONErr(canonical bool) (string, error) {
774+
// We don't check for a nil document here because that's the first thing
775+
// that MarshalBSON does.
776+
b, err := d.MarshalBSON()
777+
if err != nil {
778+
return "", err
779+
}
780+
781+
return ToExtJSON(canonical, b)
782+
}

bson/document_test.go

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -891,6 +891,37 @@ func TestDocument(t *testing.T) {
891891
}
892892
}
893893
})
894+
t.Run("ToExtJSON", func(t *testing.T) {
895+
t.Run("Marshaling Error", func(t *testing.T) {
896+
var doc *Document
897+
_, err := doc.ToExtJSONErr(false)
898+
if err != ErrNilDocument {
899+
t.Errorf("Did not receive expected error. got %v; want %v", err, ErrNilDocument)
900+
}
901+
})
902+
t.Run("Canonical", func(t *testing.T) {
903+
doc := NewDocument(EC.String("hello", "world"), EC.Double("pi", 3.14159))
904+
want := `{"hello":"world","pi":{"$numberDouble":"3.14159"}}`
905+
got, err := doc.ToExtJSONErr(true)
906+
if err != nil {
907+
t.Errorf("Unexpected error while converting document to extended json: %v", err)
908+
}
909+
if got != want {
910+
t.Errorf("Did not recieve expected result. got %s; want %s", got, want)
911+
}
912+
})
913+
t.Run("Relaxed", func(t *testing.T) {
914+
doc := NewDocument(EC.String("hello", "world"), EC.Double("pi", 3.14159))
915+
want := `{"hello":"world","pi":3.14159}`
916+
got, err := doc.ToExtJSONErr(false)
917+
if err != nil {
918+
t.Errorf("Unexpected error while converting document to extended json: %v", err)
919+
}
920+
if got != want {
921+
t.Errorf("Did not recieve expected result. got %s; want %s", got, want)
922+
}
923+
})
924+
})
894925
}
895926

896927
func testDocumentKeys(t *testing.T) {

0 commit comments

Comments
 (0)