-1

So I'm trying to query from a table in my db. I'm using python btw. I want to return them as JSON over a loop.

But I only return one row from my table, which looks like this:

{
    "content": "content1", 
    "date": "date1", 
    "title": "title1"
}

Here's my code:

ann = Announcements.query.all()

for data in ann:
    return jsonify({'date': data.date, 'title': data.title, 'content': data.content })

I want to return something like this:

{
    "content": "content1", 
    "date": "date1", 
    "title": "title1"
},
{
    "content": "content2", 
    "date": "date2", 
    "title": "title2"
},
{
    "content": "content3", 
    "date": "date3", 
    "title": "title3"
}

What am I missing here?

Lee Merlas
  • 430
  • 9
  • 24
  • 2
    You have a `return` inside your for loop, so your loop will terminate after only one iteration. You probably want to create a list, then in your loop append your dictionary to the list. After the loop return the json-encoded list. – snakecharmerb Apr 29 '18 at 09:56

1 Answers1

2

I think you should create a list firstly. And append all your data and jsonify. If you return jsonify you should use method.

def jsonify(ann):
    my_list = []
    for data in ann:
      my_list.append({'date': data.date, 'title': data.title, 'content': data.content })
    return jsonify(my_list)

Otherwise you should print in a loop your data like this

for data in ann:
   print(jsonify({'date': data.date, 'title': data.title, 'content': data.content }))

Look at this for more details

Ahmet Sina Ustem
  • 1,090
  • 15
  • 32