Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert SQL into json in Python [duplicate]

Tags:

python

json

sql

I need to pass an object that I can convert using $.parseJSON. The query looks like this:

cursor.execute("SELECT earnings, date FROM table")

What do I need to do from here in order to pass an HttpResponse object that can be converted into json?

like image 652
David542 Avatar asked May 31 '12 18:05

David542


1 Answers

Well, if you simply do:

json_string = json.dumps(cursor.fetchall())

you'll get an array of arrays...

[["earning1", "date1"], ["earning2", "date2"], ...]

Another way would be to use:

json_string = json.dumps(dict(cursor.fetchall()))

That will give you a json object with earnings as indexes...

{"earning1": "date1", "earning2": "date2", ...}

If that's not what you want, then you need to specify how you want your result to look...

like image 108
mata Avatar answered Sep 28 '22 03:09

mata