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

梦想的初衷 提交于 2019-12-24 05:04:13

问题


I'm using flask with the following model:

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")

And I want to create a json object from this model for use in navigation menu.

I would like to parse it recursively and build a hierarchical JSON object that looks something like this:

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"}
          ]}
        ]

回答1:


I use a library called Flask-Restless for querying the database and returning json. It's made to work with SQLAlchemy.

If you're not looking to integrate with something like this, you can subclass your SQLAlchemy model and just run to_json() method on it.

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

Credit: Github Overholt project (author of Flask-Security)



来源:https://stackoverflow.com/questions/30367450/how-to-create-a-json-object-from-tree-data-structure-in-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!