Python 将GAE模型转换为JSON
我正在使用将GAE模型转换为JSON:Python 将GAE模型转换为JSON,python,google-app-engine,Python,Google App Engine,我正在使用将GAE模型转换为JSON: def to_dict(self): return dict([(p, unicode(getattr(self, p))) for p in self.properties()]) 它工作得很好,但是如果属性没有值,它会将默认字符串设置为“None”,这在我的客户端设备(Objective-C)中被解释为真实值,即使它应该被解释为nil值 如何在保持代码简洁的同时修改上面的代码,使其跳过没有值的属性,而不将属性写入字典 def to_dict(
def to_dict(self):
return dict([(p, unicode(getattr(self, p))) for p in self.properties()])
它工作得很好,但是如果属性没有值,它会将默认字符串设置为“None”,这在我的客户端设备(Objective-C)中被解释为真实值,即使它应该被解释为nil值
如何在保持代码简洁的同时修改上面的代码,使其跳过没有值的属性,而不将属性写入字典
def to_dict(self):
return dict((p, unicode(getattr(self, p))) for p in self.properties()
if getattr(self, p) is not None)
您不需要首先创建列表(周围的[]
),您只需使用一个来动态构建值
它不是很简单,但是如果您的模型结构变得更复杂,您可能需要看看这个递归变量:
# Define 'simple' types
SIMPLE_TYPES = (int, long, float, bool, dict, basestring, list)
def to_dict(model):
output = {}
for key, prop in model.properties().iteritems():
value = getattr(model, key)
if isinstance(value, SIMPLE_TYPES) and value is not None:
output[key] = value
elif isinstance(value, datetime.date):
# Convert date/datetime to ms-since-epoch ("new Date()").
ms = time.mktime(value.utctimetuple())
ms += getattr(value, 'microseconds', 0) / 1000
output[key] = int(ms)
elif isinstance(value, db.GeoPt):
output[key] = {'lat': value.lat, 'lon': value.lon}
elif isinstance(value, db.Model):
# Recurse
output[key] = to_dict(value)
else:
raise ValueError('cannot encode ' + repr(prop))
return output
通过添加到elif
分支,这可以很容易地扩展到其他非简单类型