Convert GAE Model to JSON

I use the code found here to convert the GAE model to JSON:

def to_dict(self):
    return dict([(p, unicode(getattr(self, p))) for p in self.properties()])

It works fine, but if the property does not matter, it puts the default string “None” and this is interpreted as the real value on my client device (Objective-C), although it should be interpreted as the value nil.

How can I change the code above while keeping it concise so that I don't skip and write properties to a dictionary that has None values?

+3
source share
1 answer
def to_dict(self):
    return dict((p, unicode(getattr(self, p))) for p in self.properties()
                if getattr(self, p) is not None)

You do not need to create a list (surrounding []) first, you can just use an expression to create a value on the fly.

, - , :

# 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.

+7

All Articles