簡體   English   中英

如何從數據庫中的樹數據結構創建json對象?

[英]how to create a json object from tree data structure in database?

我正在使用以下型號的燒瓶:

class NewsCategory(db.Model):
    __tablename__ = 'news_category'
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(64))
    parent_id = db.Column(db.Integer, db.ForeignKey('news_category.id'))
    children = db.relationship("NewsCategory")

我想從此模型創建一個json對象,以在導航菜單中使用。

我想遞歸解析它,並構建一個看起來像這樣的分層JSON對象:

tree = [{"title": "Node 1", "id": "1"},
         {"title": "Folder 2", "id": "2", "folder": "true", "children": [
            {"title": "Node 2.1", "id": "3"},
            {"title": "Node 2.2", "id": "4"}
          ]}
        ]

我使用一個名為Flask-Restless的庫來查詢數據庫並返回json。 它可以與SQLAlchemy一起使用。

如果您不希望與此類集成,則可以將SQLAlchemy模型子類化,然后在其上運行to_json()方法。

class NewsCategory(db.Model, JsonSerializer)

class JsonSerializer(object):
    """A mixin that can be used to mark a SQLAlchemy model class which
    implements a :func:`to_json` method. The :func:`to_json` method is used
    in conjuction with the custom :class:`JSONEncoder` class. By default this
    mixin will assume all properties of the SQLAlchemy model are to be visible
    in the JSON output. Extend this class to customize which properties are
    public, hidden or modified before being being passed to the JSON serializer.
    """

    __json_public__ = None
    __json_hidden__ = None
    __json_modifiers__ = None

    def get_field_names(self):
        for p in self.__mapper__.iterate_properties:
            yield p.key

    def to_json(self):
        field_names = self.get_field_names()

        public = self.__json_public__ or field_names
        hidden = self.__json_hidden__ or []
        modifiers = self.__json_modifiers__ or dict()

        rv = dict()
        for key in public:
            rv[key] = getattr(self, key)
        for key, modifier in modifiers.items():
            value = getattr(self, key)
            rv[key] = modifier(value, self)
        for key in hidden:
            rv.pop(key, None)
        return rv

圖片提供: Github Overholt項目 (Flask-Security的作者)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM