I'm parsing BSON from strings using the mongo driver library.
AFAIK, the following should be valid BSON:
{
"createdAt": {"$date": "2024-01-01T00:00:00.000Z"}
}
but the following test code
var v bson.M
bsonString = `{"createdAt": {"$date": "2024-01-01T00:00:00.000Z"}}`
err := bson.UnmarshalExtJSON([]byte(bsonString), true, &v)
if err != nil {
t.Fatalf("cannot unmarshal: %v", err)
}
fails with error
cannot unmarshal: error decoding key createdAt: invalid JSON input; expected {
Why?
I'm parsing BSON from strings using the mongo driver library.
AFAIK, the following should be valid BSON:
{
"createdAt": {"$date": "2024-01-01T00:00:00.000Z"}
}
but the following test code
var v bson.M
bsonString = `{"createdAt": {"$date": "2024-01-01T00:00:00.000Z"}}`
err := bson.UnmarshalExtJSON([]byte(bsonString), true, &v)
if err != nil {
t.Fatalf("cannot unmarshal: %v", err)
}
fails with error
cannot unmarshal: error decoding key createdAt: invalid JSON input; expected {
Why?
Share Improve this question asked Jan 31 at 10:19 AleGAleG 1501 silver badge9 bronze badges 3 |1 Answer
Reset to default 2In bson.UnmarshalExtJSON
, set canonicalOnly
to false
since Canonical-mode requires dates to be represented as quoted numbers (strings), being milliseconds relative to the epoch.
From the Extended JSON v2 reference:
Canonical:
{"$date": {"$numberLong": "<millis>"}}
Relaxed:
{"$date": "<ISO-8601 Date/Time Format>"}
And
Where the values are as follows:
"<millis>"
- A 64-bit signed integer as string. The value represents milliseconds relative to the epoch.
So presumably negative numbers for "before 1970".
Go Playground example, output with canonicalOnly=false
:
{"createdAt":{"$date":{"$numberLong":"1704067200000"}}}
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745269281a4619645.html
bson.UnmarshalExtJSON
is for Extended JSON, not BSON. If it was actually BSON, usebson.Unmarshal
2. SetcanonicalOnly = false
since Canonical mode requires dates to be numbers. 3. You are unmarshalling{ "createdAt": {"$date": ... } }
not just the$date
part. I don't know if that's related to the error or how unmarshalling handles nested objects. – aneroid Commented Jan 31 at 10:47canonicalOnly
flag, then the example is correct and doesn't need simplification. (Wrt 2. Answer posted with more info.) – aneroid Commented Jan 31 at 11:54