[GODRIVER-1332] primitive.ObjectID json omitempty doesn't work Created: 04/Oct/19  Updated: 27/Oct/23  Resolved: 07/Oct/19

Status: Closed
Project: Go Driver
Component/s: BSON
Affects Version/s: None
Fix Version/s: None

Type: Bug Priority: Major - P3
Reporter: Ed Pelc Assignee: Divjot Arora (Inactive)
Resolution: Works as Designed Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified


 Description   

package main
 
import (
	"encoding/json"
	"fmt"
 
	"go.mongodb.org/mongo-driver/bson/primitive"
)
 
func main() {
	td := struct {
		EmptyExample primitive.ObjectID `json:",omitempty"`
	}{}
 
	out, err := json.Marshal(td)
	if err != nil {
		panic(err)
	}
 
	fmt.Println(string(out))
}

You get the following output `

{"EmptyExample":"000000000000000000000000"}

` instead of an omitted field because the `ObjectID` type is an alias for a 12 byte slice and it doesn't have a custom json marshaler.



 Comments   
Comment by Divjot Arora (Inactive) [ 07/Oct/19 ]

Hi epelc@greatcloak.com,

Thank you for your bug report and investigation. In addition to the issue you linked, I also found https://github.com/golang/go/issues/29310. The underlying issue is that omitempty only considers an array to be empty if it is of length 0, which is never true for the ObjectID type. By the time ObjectID.MarshalJSON is called, the encoding/json library has already determined that the value is not zero and therefore will not be omitted. Furthermore, there is nothing that our MarhsalJSON function can return to indicate that the value is zero and should not be marshalled (returning an empty []byte causes a panic in the json code). As a result, I'm going to close this ticket. If you find anything helpful or if the encoding/json library changes to allow this behavior, feel free to re-open.

 

– Divjot

Comment by Ed Pelc [ 04/Oct/19 ]

Upon further inspection you can not fix this by modifying `func (id ObjectID) MarshalJSON()` since the go json lib doesn't support it.

https://github.com/golang/go/issues/11939

Generated at Thu Feb 08 08:36:11 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.