jva*_*nor 2 google-app-engine json python-2.7 app-engine-ndb google-cloud-datastore
我有一个我想要转换为JSON的ndb.Model.
class Users(ndb.Model):
username = ndb.StringProperty(indexed=True)
password= ndb.StringProperty(indexed=True)
created_at = ndb.DateTimeProperty(auto_now_add=True)
user = Users.query(Users.username==username).get()
rv = json.dumps(user.to_dict())
print(rv)
Run Code Online (Sandbox Code Playgroud)
它抛出此错误:
TypeError: datetime.datetime(2013, 11, 24, 3, 40, 15) is not JSON serializable
Run Code Online (Sandbox Code Playgroud)
这里的大多数解决方案都是针对db.Model的,并且已经过时了.
sdk版本1.9.10
Max*_*kov 10
您可以扩展Property类以处理特殊情况.它适用于任何房产类型.
from google.appengine.ext import ndb
class DateTimeProperty(ndb.DateTimeProperty):
# Override to allow JSON serialization
def _get_for_dict(self, entity):
value = super(DateTimeProperty, self)._get_for_dict(entity);
return value.isoformat()
Run Code Online (Sandbox Code Playgroud)
然后在您的模型中使用它:
class Users(ndb.Model):
username = ndb.StringProperty(indexed=True)
password= ndb.StringProperty(indexed=True)
created_at = DateTimeProperty(auto_now_add=True)
Run Code Online (Sandbox Code Playgroud)
而且to_dict(),你通常会做:
user = Users.query(Users.username==username).get()
user.to_dict()
Run Code Online (Sandbox Code Playgroud)
您需要一个自定义的"to JSON"转换器来处理JSON本身不支持的格式.
我正在使用类似下面的代码来处理大多数情况.
def to_json(self, o):
if isinstance(o, list):
return [self.to_json(l) for l in o]
if isinstance(o, dict):
x = {}
for l in o:
x[l] = self.to_json(o[l])
return x
if isinstance(o, datetime.datetime):
return o.isoformat()
if isinstance(o, ndb.GeoPt):
return {'lat': o.lat, 'lon': o.lon}
if isinstance(o, ndb.Key):
return o.urlsafe()
if isinstance(o, ndb.Model):
dct = o.to_dict()
dct['id'] = o.key.id()
return self.to_json(dct)
return o
Run Code Online (Sandbox Code Playgroud)
所以在我的情况下,我也在处理其他一些事情,比如GeoPt,并为所有ndb.Model添加一个ID字段,但对于你的情况,你需要的只是:
if isinstance(o, datetime.datetime):
return o.isoformat()
Run Code Online (Sandbox Code Playgroud)
但我猜(不确定)你会得到一个关键错误,所以你也需要
if isinstance(o, ndb.Key):
return o.urlsafe()
Run Code Online (Sandbox Code Playgroud)
如果您不需要created_at字段,您可以简单地将其排除
rv = json.dumps(user.to_dict(exclude=['created_at']))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2181 次 |
| 最近记录: |