Search code examples
mysqljsonlambdapymysql

Why is my json built using PyMySQL returning with duplicate results?


I am running a select statement on my MySQL database using PyMySQL and then using some code to build a json output which is then being returned from the lambda function to my mobile app.

The problem is that while testing I've discovered that the json which is being built has duplicates for each row of data.

There should be 10 rows returned but I have 104.

This is the relevant part of the code:

search_sql = f"SELECT * FROM Games"
cur.execute(search_sql)
rows = cur.fetchall()

result = []
for row in rows:
    d = {}
    for i, col in enumerate(cur.description):
        d[col[0]] = row[i]
        result.append(d)
return result

I should also mention that I have checked in the database and there are definitely only 10 distinct rows.


Solution

  • What you're doing is looping twice, calling result.append(d) 10x as often as you expect. Indent it back one.