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

问题描述 投票:0回答:2

我想使用Python中的库

mysql-connector
json
将带有一张表的mysql数据库导出为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
python json python-3.x mysql-connector
2个回答
2
投票

如果您有无法序列化为 JSON 的对象,您可以在

default=str
上使用
json.dumps

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


0
投票

我将表的排序规则更新为 utf8mb3_unicode_ci

alter table MyTable convert to character set utf8mb3 collate utf8mb3_unicode_ci;

我使用这个Python代码来获得json结果

@app.route("/records")
def get_records():
    mydb = mysql.connector.connect(host="localhost",user="me",password="xxx",database="mydb")
    cursor = mydb.cursor(dictionary=True)
    query = "SELECT * FROM records"
    cursor.execute(query)
    result = cursor.fetchall()
    return result
© www.soinside.com 2019 - 2024. All rights reserved.