【问题标题】:how to create a json object from tree data structure in database?如何从数据库中的树数据结构创建 json 对象?
【发布时间】:2015-08-02 18:00:03
【问题描述】:

我正在使用以下型号的烧瓶:

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

【问题讨论】:

  • 请包括您尝试过的内容。有用吗?

标签: python json flask sqlalchemy uinavigationbar


【解决方案1】:

我使用一个名为 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 project(Flask-Security 的作者)

【讨论】:

  • 我有和上面一样的用例,所以我用NewsCategory().to_json()尝试了这个,但是得到了一个空字典,就像{'title': None, 'id': None, 'parent_id': None, 'children': []}一样...我已经验证数据在底层表也​​。我感觉我对 to_json() 方法的调用不正确。
  • @horcle_buzz 此方法旨在用于现有对象 - 您是否尝试在空对象上使用它? news_cat = NewsCategory.query.filter_by(name='Technology').first() news_cat_json = news_cat.to_json() 希望这有助于澄清。
  • 嗨。我实际上使用 Marshmallow 库中提供的嵌套方案解决了我的问题。实现起来非常简单。是的,该对象确实作为 SQLAlchemy 对象存在。
猜你喜欢
  • 1970-01-01
  • 2019-12-23
  • 2012-12-14
  • 2020-10-03
  • 2013-05-25
  • 1970-01-01
  • 2019-08-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多