Skip to content

Instantly share code, notes, and snippets.

@henrahmagix
Last active February 17, 2020 11:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save henrahmagix/8087aff39246ebe48fd247faddcca627 to your computer and use it in GitHub Desktop.
Save henrahmagix/8087aff39246ebe48fd247faddcca627 to your computer and use it in GitHub Desktop.
How to get any data from Google Datastore as an untyped map
package main
type DynamicEntity map[string]interface{}
func (d *DynamicEntity) Load(props []datastore.Property) error {
loadMap(*d, props)
return nil
}
func loadMap(m map[string]interface{}, props []datastore.Property) {
for _, prop := range props {
if nested, ok := prop.Value.(*datastore.Entity); ok {
mm := make(map[string]interface{})
loadMap(mm, nested.Properties)
m[prop.Name] = mm
} else if nestedArray, ok := prop.Value.([]interface{}); ok {
arr := make([]interface{}, len(nestedArray))
for i, nested := range nestedArray {
mm := make(map[string]interface{})
loadMap(mm, nested.(*datastore.Entity).Properties)
arr[i] = mm
}
m[prop.Name] = arr
} else {
m[prop.Name] = prop.Value
}
}
}
func (d *DynamicEntity) Save() ([]datastore.Property, error) {
return nil, nil
}
package main
import (
"context"
"fmt"
"cloud.google.com/go/datastore"
)
func main() {
ctx := context.Background()
ds, err := datastore.NewClient(ctx, "my-project-id")
handleErr(err)
myEntityMap := make(DynamicEntity)
err = ds.Get(ctx, datastore.IDKey("MyEntity", 1234, nil), &myEntityMap)
fmt.Printf("myEntityMap: %+v\n", myEntityMap)
myField := myEntityMap["MyField"].(string)
fmt.Println("MyField", myField)
myNestedField := myEntityMap["NestedEntity"].(map[string]interface{})["NestedField"].(string)
fmt.Println("NestedEntity.NestedField", myNestedField)
}
func handleErr(err error) {
if err != nil {
panic(err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment