【问题标题】:How can I return a nested json using flask.jsonify by querying a database?如何通过查询数据库使用 flask.jsonify 返回嵌套的 json?
【发布时间】:2018-10-02 17:26:22
【问题描述】:

这是我的数据库表架构

Movie (id, movie_name, genre, time, channel)

我有一个MySQL 表,并希望将嵌套的json 返回到 API,并按流派和频道对它们进行分组。

例如:

[
    'comedy': {
        [{'id': 1, 'movie_name': 'm1', 'time': 18:00, 'channel': 'c1'},
         {'id': 1, 'movie_name': 'm2', 'time': 18:00, 'channel': 'c2'}]
    },
    'horror': {
        [{'id': 1, 'movie_name': 'm3', 'time': 18:00, 'channel': 'c1'},
         {'id': 1, 'movie_name': 'm4', 'time': 18:00, 'channel': 'c2'}]
    }
]

对于每个频道也是如此。

更新:我没有使用 SQL-Alchemy,我现在所做的只是return jsonify(cursor.fetchall())

【问题讨论】:

    标签: python mysql python-3.x api flask


    【解决方案1】:

    假设您使用的是 SQLAlchemy ORM

    comedies = []
    horrors =[] #for lack of a better way to put it
    all_movies = session.query(Movie)
    for movie in all_movies:
       if movie.genre == 'comedy':
          comedy_entry ={'id':movie.id,
                          'movie_name':movie.movie_name,
                          'time':movie.time,
                          'channel': movie.channel }
          comedies.append(comedy_entry)
       if movie.genre == 'horror':
          horror_entry ={'id':movie.id,
                          'movie_name':movie.movie_name,
                          'time':movie.time,
                          'channel': movie.channel }
          horrors.append(horror_entry)
    
    return jsonify({'comedy'= comedies, 'horror'= horrors})
    

    我希望能指导你或至少给你一个起点

    【讨论】:

    • 感谢您的解决方案,但您能否建议我一个不使用 SQL-Alchemy 的替代解决方案?
    • @SagunShrestha 请参阅this answer,了解如何连接到 mysql 数据库。如果您不想使用 SQLAlchemy,答案 3 看起来最好。 results 成为你迭代的结果(相当于上面所有的电影)
    【解决方案2】:

    这是另一种更可扩展的方法:

    columns_to_be_jsonified = ['id', 'movie_name', 'time']
    genredict = {}
    
    for movie in Movie.query.all():
        movietup = movie.genre, movie.channel
        moviedict = {}
        for column in columns_to_be_jsonified:
            moviedict[column] = getattr(movie, column)
    
        if movietup in genredict:
            genredict[movietup].append(moviedict)
        else:
            genredict[movietup] = [moviedict]
    
    return jsonify(genredict)
    

    返回

    {('horror', 'channel1'): [{'id': 1, 'movie_name': 'it', 'time': '18:00'}, {'id': 2, 'movie_name': 'the ring', 'time': '20:00'}],
     ('comedy', 'channel2'): [...]}
    

    【讨论】:

    • 感谢您的解决方案,但您能否建议我一个不使用 SQL-Alchemy 的替代解决方案?
    猜你喜欢
    • 1970-01-01
    • 2013-08-10
    • 2020-08-05
    • 1970-01-01
    • 1970-01-01
    • 2020-12-30
    • 1970-01-01
    • 1970-01-01
    • 2023-02-04
    相关资源
    最近更新 更多