1

I've tried reading the docs here and following the answers here but neither worked.

Here's what I put into datastore:

{'a': 'b', 'c': {'d': 'f'}}

If I query it I get:

<Entity('MyKind', 1232141232id) {'a': 'b', 'c': <Entity {'d': 'f'}>}>

I'm using google-cloud-python (which is recommended in docs) instead of ndb so I can't use:

from google.appengine.ext import db
db.to_dict(entity)

If I try to cast dict(results[0]) I get:

{'a': 'b', 'c': <Entity {'d': 'f'}>}

^^ This is almost what I need except for the nested Entity.

Any recommendations for the best way to do this? It seems like there would be a function for this but I just can't find it.

Dustin Ingram
  • 15,737
  • 2
  • 40
  • 56
RayB
  • 1,460
  • 3
  • 19
  • 34

2 Answers2

1

The best solution I've found so far was this but not sure if this would break from any edge cases.

import json
json.loads(json.dumps(data), parse_int=str)
RayB
  • 1,460
  • 3
  • 19
  • 34
1

So Entity itself inherits from dict and adds only a few functions on top

https://googleapis.dev/python/datastore/latest/_modules/google/cloud/datastore/entity.html#Entity

Your json solution could be fine, but it depends on what the goal is. If you're ultimately just trying to convert to json then it should be fine, but you're not capturing entity.key and maybe that's something you want. Also i think json will fail for datetime objects and foreign keys unless you explicitly handle those somehow.

You probably need to build a util function like this:

def _coerce_value(v):
    if isinstance(v, Entity):
        return_value[k] = entity_to_dict(v)
    elif isinstance(v, Key):
        return v.id  # or do something else here
    return v

def entity_to_dict(entity):
    return_value = {}
    if entity.key:
        return_value['key'] = _coerce_value(entity.key)
    for k, v in entity.iteritems():
        if isinstance(v, list):  # handle repeated properties                 
            return_value[k] = [_coerce_value(i) for i in v]
        else:
            return_value[k] = _coerce_value(v)
    return return_value
Alex
  • 4,510
  • 8
  • 24