To convert a Firestore cloud event that is formatted in protojson into a map[string]interface{} or a struct using unmarshalling, you can follow these steps:
type FirestoreEvent struct {
OldValue *firestore.Value `json:"oldValue"`
Value *firestore.Value `json:"value"`
UpdateMask struct {
FieldPaths []string `json:"fieldPaths"`
} `json:"updateMask"`
// Add other fields as needed.
}
func unmarshalFirestoreEvent(data []byte) (*FirestoreEvent, error) {
var event FirestoreEvent
err := protojson.Unmarshal(data, &event)
if err != nil {
return nil, err
}
return &event, nil
}
data := []byte(`{
"oldValue": null,
"value": {
"mapValue": {
"fields": {
"name": {
"stringValue": "Alice"
},
"age": {
"integerValue": "30"
}
}
}
},
"updateMask": {
"fieldPaths": [
"name",
"age"
]
}
}`)
event, err := unmarshalFirestoreEvent(data)
if err != nil {
fmt.Println("Error:", err)
} else {
fmt.Println("Event:", event)
}
The output should be:
Event: &{<nil> 0xc0000de1a0 {<nil> map[name:mapValue age:mapValue]} {[]}}
You can then access the fields of the Firestore cloud event in the struct using dot notation, such as event.UpdateMask.FieldPaths
. If you prefer to use a map[string]interface{}, you can convert the struct to a map with json.Marshal
and json.Unmarshal
, but using a struct is generally easier and more type-safe.
Asked: 2023-06-03 06:49:34 +0000
Seen: 7 times
Last updated: Jun 03 '23