如何使用来自 PYTHON 的 mysql-connector 将 MySQL 数据库导出到 json?

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

我想使用 python 中的库 mysql-connectorjson 将一个 mysql 数据库导出到 table 至 json。

我试过的:

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 (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

如果您的对象无法序列化为 JSON

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