Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rows returned by pyodbc are not JSON serializable

Tags:

I am trying to retrieve the rows of a table using pyobc library in Python.

I was able to retrieve the tables and fields of a table successfully. Now I have a table named "apx_roomtypes" with the data as follows,

enter image description here

However, when I append the pyodbc rows to a list and then try dumping the list to JSON I get the error

TypeError: (1, 'Standard', 'For 5 members', 123) is not JSON serializable

Here is the python code:

class execute_query:
    def GET(self,r):
          web.header('Access-Control-Allow-Origin',      '*')
          web.header('Access-Control-Allow-Credentials', 'true')
          cnxn = pyodbc.connect(connection_string)
          data = []
          cursor = cnxn.cursor()
          query = web.input().query
          cursor.execute(query)
          rows = cursor.fetchall()
          for row in rows:
              data.append(row)
          return json.dumps(data)

How can i fix this error?

like image 559
Sajeetharan Avatar asked Jan 11 '16 06:01

Sajeetharan


People also ask

Why is datetime not JSON serializable?

The Python "TypeError: Object of type datetime is not JSON serializable" occurs when we try to convert a datetime object to a JSON string. To solve the error, set the default keyword argument to str in your call to the json. dumps() method. Here is an example of how the error occurs.

Is not JSON serializable?

The Python "TypeError: Object of type function is not JSON serializable" occurs when we try to serialize a function to JSON. To solve the error, make sure to call the function and serialize the object that the function returns.

How do you serialize a Date object in Python?

Serialize datetime by converting it into String You can convert dateTime value into its String representation and encode it directly, here you don't need to write any encoder. We need to set the default parameter of a json. dump() or json. dumps() to str like this json.


1 Answers

When you are iterating over rows, each row is a Row instance and not a list. You can convert it to a list (which is JSON serializable) as follows:

rows = cursor.fetchall()
for row in rows:
    data.append([x for x in row]) # or simply data.append(list(row))

If you want it to return a dictionary of key/value pairs instead of a list of values then take a look at this answer.

like image 111
14 revs, 12 users 16% Avatar answered Sep 23 '22 16:09

14 revs, 12 users 16%