I am using SQLalchemy and flask API to develop my school project, the original code:
@app.route('/test/',methods=['GET'])
def search_item():
result=engine.execute(
'SQL query codes'
)
test=result.fetchall()
...
return tmp
for the ... part above I have tried following steps, and this is the data looks like, which I have fetched from the db and converted to list.
test=[('01','Bob','Engineer','M'),('02','Jacob','Cook','M'),('03','Amy','Teacher','F')]
I appended the index by using for loop and i=i 1 method, since looks like you can directly transfer dict to json.
test=[0,('01','Bob','Engineer','M'),1,('02','Jacob','Cook','M'),2,('03','Amy','Teacher','F')]
and it successfully converted to dict like below, by using:
sh=iter(test)
test=dict(zip(sh,sh))
output, and I have checked the type(test) is dict:
test={0:('01','Bob','Engineer','M'),1:('02','Jacob','Cook','M'),2:('03','Amy','Teacher','F')}
but when I want to convert it to json, error happened, it shows this error message:
TypeError: Object of type LegacyRow is not JSON serializable
I am using this code for converting json:
tmp=json.dumps(test)
Thank you!
CodePudding user response:
The result you get from your query gets printed as if it is a tuple, but in reality it is of type LegacyRow causing an error later.
Try to do this after fetching the result:
test=[tuple(elem for elem in item) for item in test]
test
should look the same but now you have actual tuples that are serializable.