I’m using the code found here to convert a GAE model into JSON:
def to_dict(self):
return dict([(p, unicode(getattr(self, p))) for p in self.properties()])
It works just fine, but if a property does not have a value, it puts a default string of “None”, and this is interpreted as a real value in my client device (Objective-C), even though it should be interpreted as a nil value.
How can I modify the code above while maintaining its brevity to skip over and not write properties to the dictionary that have None values?
You don’t need to create a list first (the surrounding
[]), you can just use a generator expression to build the values on-the-fly.It’s not quite brief, but if your model structure ever gets a bit more complex, you may want to look at this recursive variant:
This could be easily extended with other non-simple types by adding to the
elifbranches.