0

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

Sagun Shrestha
  • 1,188
  • 10
  • 23

2 Answers2

1

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

Moses N. Njenga
  • 762
  • 1
  • 9
  • 19
  • Thank you for your solution but can you suggest me an alternative solution without using SQL-Alchemy? – Sagun Shrestha Apr 23 '18 at 04:52
  • @SagunShrestha please see [this answer](https://stackoverflow.com/questions/9845102/using-mysql-in-flask) on how you can connect to mysql database. Answer 3 looks best if you do not want to use SQLAlchemy. The _results_ becomes what you iterate over (equivalent to all movie's above) – Moses N. Njenga Apr 23 '18 at 07:05
0

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'): [...]}
Joost
  • 3,609
  • 2
  • 12
  • 29