JSON serialization of Google App Engine models

后端 未结 14 2124
不知归路
不知归路 2020-12-04 04:59

I\'ve been searching for quite a while with no success. My project isn\'t using Django, is there a simple way to serialize App Engine models (google.appengine.ext.db.Model)

14条回答
  •  无人及你
    2020-12-04 05:49

    I've extended the JSON Encoder class written by dpatru to support:

    • Query results properties (e.g. car.owner_set)
    • ReferenceProperty - recursively turn it into JSON
    • Filtering properties - only properties with a verbose_name will be encoded into JSON

      class DBModelJSONEncoder(json.JSONEncoder):
          """Encodes a db.Model into JSON"""
      
          def default(self, obj):
              if (isinstance(obj, db.Query)):
                  # It's a reference query (holding several model instances)
                  return [self.default(item) for item in obj]
      
              elif (isinstance(obj, db.Model)):
                  # Only properties with a verbose name will be displayed in the JSON output
                  properties = obj.properties()
                  filtered_properties = filter(lambda p: properties[p].verbose_name != None, properties)
      
                  # Turn each property of the DB model into a JSON-serializeable entity
                  json_dict = dict([(
                          p,
                          getattr(obj, p)
                              if (not isinstance(getattr(obj, p), db.Model))
                              else
                          self.default(getattr(obj, p)) # A referenced model property
                      ) for p in filtered_properties])
      
                  json_dict['id'] = obj.key().id() # Add the model instance's ID (optional - delete this if you do not use it)
      
                  return json_dict
      
              else:
                  # Use original JSON encoding
                  return json.JSONEncoder.default(self, obj)
      

提交回复
热议问题