dimanche 4 juillet 2021

Save map[string]interface{} to datastore [duplicate]

My program reads a JSON file that mainly looks like this:

{
  "a": "b",
  "c": 123,
  "d": ["e", "f"],
  "g": {"h": "i"}
}

The structure of this data is dynamic, so I use a map[string]interface{} to read it because of the different value types.

type Map map[string]interface{}

I need to save this JSON structure to datastore, but I keep getting this error datastore: invalid entity type. I guess this is because my Map type needs to implement that PropertyLoadSaver interface, so I tried the following code and it still returns the same error.

func (e Entity) Save(c chan<- datastore.Property) error {
    defer close(c)
    for k, v := range e {
        value, err := json.Marshal(v)
        if err != nil {
            log.Fatal(err)
        }
        c <- datastore.Property{
            Name:  k,
            Value: value,
        }
    }
    return nil
}

func (m Entity) Load(c <-chan datastore.Property) error {
    // I won't actually be loading the data in this program; just saving, so I think I can get away with this?
    return nil
}

Any ideas what the correct way to do this is?





Aucun commentaire:

Enregistrer un commentaire