【问题标题】:Converting GAE model into JSON将 GAE 模型转换为 JSON
【发布时间】:2012-05-27 09:33:58
【问题描述】:

我正在使用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 值。

如何修改上面的代码,同时保持其简洁性以跳过并且不将属性写入具有 None 值的字典?

【问题讨论】:

    标签: python google-app-engine


    【解决方案1】:
    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 分支,可以很容易地使用其他非简单类型进行扩展。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-10
      • 2019-11-15
      • 2014-06-30
      • 1970-01-01
      相关资源
      最近更新 更多