Search code examples
pythonjsonpython-3.xmysql-connector

How to export a MySQL database to json using mysql-connector from PYTHON?


I want to export a mysql database with one table to json using the libraries mysql-connector and json from python.

What I tried:

import mysql-connector, json

cursor.execute("SELECT * FROM records")
data=cursor.fetchall()
for e in data:
  print(json.dumps(data, sort_keys=True, indent=4, separators=(',', ': ')))

Traceback error:

Traceback (most recent call last):
  File "bsentor.py", line 238, in <module>
    print(json.dumps(data))
  File "C:\Users\Justo Gregorio\AppData\Local\Programs\Python\Python37\lib\json\__init__.py", line 231, in dumps
    return _default_encoder.encode(obj)
  File "C:\Users\Justo Gregorio\AppData\Local\Programs\Python\Python37\lib\json\encoder.py", line 199, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "C:\Users\Justo Gregorio\AppData\Local\Programs\Python\Python37\lib\json\encoder.py", line 257, in iterencode
    return _iterencode(o, 0)
  File "C:\Users\Justo Gregorio\AppData\Local\Programs\Python\Python37\lib\json\encoder.py", line 179, in default
    raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type date is not JSON serializable

Solution

  • You can use default=str on json.dumps If you have objects not serializable to JSON

    cursor.execute("SELECT * FROM registros")
    data=cursor.fetchall()
    for e in data:
      print(json.dumps(data, sort_keys=True, indent=4, separators=(',', ': '), default=str))