简体   繁体   中英

How can I return a nested json using flask.jsonify by querying a database?

Here is what my database table schema

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

I have a MySQL table and want to return a nested json to an API, grouping them by genre and channel.

For example:

[
    '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'}]
    }
]

And similarly for each channels.

Update: I am not using SQL-Alchemy, all I am doing now is return jsonify(cursor.fetchall())

Assuming you are using 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})

I hope that guides you or at least gives you a starting point

Here is another, more extendible approach:

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)

It returns

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM