Skip to content

Instantly share code, notes, and snippets.

@bengrunfeld
Last active September 5, 2018 18:59
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save bengrunfeld/062d0d8360667c47bc5b to your computer and use it in GitHub Desktop.
Save bengrunfeld/062d0d8360667c47bc5b to your computer and use it in GitHub Desktop.
Convert NDB result to JSON Serializable data
def make_ndb_return_data_json_serializable(data):
"""Build a new dict so that the data can be JSON serializable"""
result = data.to_dict()
record = {}
# Populate the new dict with JSON serializiable values
for key in result.iterkeys():
if isinstance(result[key], datetime.datetime):
record[key] = result[key].isoformat()
continue
record[key] = result[key]
# Add the key so that we have a reference to the record
record['key'] = data.key.id()
return record
def filter_results(qry):
"""
Send NDB query result to serialize function if single result,
else loop through the query result and serialize records one by one
"""
result = []
# check if qry is a list (multiple records) or not (single record)
if type(qry) != list:
record = make_ndb_return_data_json_serializable(qry)
return record
for q in qry:
result.append(make_ndb_return_data_json_serializable(q))
return result
# Usage:
#
# qry = TodoModel.query().fetch()
# serialized_results = filter_results(qry)
#
# self.response.headers['Content-Type'] = 'text/plain'
# self.response.write(json.dumps(serializable_results))
#
#
# Example:
#
# For a working implemented example of this, see:
# https://github.com/bengrunfeld/gae-restful-api/blob/master/handlers.py
@claudiokc
Copy link

Thanks! Work excellent!!! Thank you very much!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment