我使用code found here将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(self):
return dict((p, unicode(getattr(self, p))) for p in self.properties()
if getattr(self, p) is not None)
您不需要首先创建列表(周围的
[]
),只需使用generator expression动态构建值。这并不十分简单,但是如果您的模型结构变得更加复杂,您可能需要看看这个递归变量:
# 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
分支,这可以很容易地扩展为其他非简单类型。