python pymysql 如何输出 json 字符串

python pymysql 如何输出 json 字符串

刚入门 python,目前在写一个比较简单的功能,不知道其它框架有没有比较简单的将数据库数据输出 json 的方式,这里说一个自定义的 json 输出功能

数据库请求

标准的一个数据请求,这里请求了日记列表中的前10个,取了日记的 id, title, content 三个字段的值

   cursor = db.cursor()
    try:
        cursor.execute('select id, title, content from diaries where uid=3 limit 10')
        results = cursor.fetchall()
        print(cursor.description)
        print(results)
    except Exception as err:
        print('error:', err)
    finally:
        db.close()

分析数据库返回的数据结构

获取到的 results 是一个元组 tuple,内容如下:

(
	(1, '《标题日记》完成输入功能', None), 
	(2, '睡了一天,有些累,秋天天气真好', None), 
	(3, '《标题日记》完成同步功能,Yeah!', None), 
	(4, '玩王者荣耀', None), 
	(5, '下雨,基本什么也没干', None), 
	(6, '饥荒口袋,修正 IPv6 连接问题', None), 
	(7, '昨晚玩游戏玩晚了,今天看电视', None), 
	(8, '还是118个俯卧撑', None), 
	(9, '陪哥哥去临朐买石头', None), 
	(10, '会做西红柿鸡蛋面', None)
)

cursor.description 中存储的是三个字段名

(
	('id', 3, None, 11, 11, 0, False), 
	('title', 252, None, 262140, 262140, 0, False), 
	('content', 252, None, 4294967295, 4294967295, 0, True)
)

知道了上面的结构,我的方案是,

  1. 新建一个 list
  2. 遍历 result
  3. 将每个 row 转化成对应 key 的 字典
    遍历 cursor.description 字段,用 index 作为获取 row 中值和 description 中值的索引
    for index in range(len(cursor.description)):  # 遍历对象内的属性,添加到 content 字典中
       key = cursor.description[index][0]
       listItem[key] = row[index]
       
    {'id': 7, 'title': '昨晚玩游戏玩晚了,今天看电视', 'content': None}
    
  4. 再用 json.dumps(obj) 生成 json 即可

完整代码如下:

cursor = db.cursor()
try:
    cursor.execute('select id, title, content from diaries where uid=3 limit 10')
    results = cursor.fetchall()
    diaryList = []
    for row in results:  # 遍历列表
        listItem = {}
        for index in range(len(cursor.description)):  # 遍历对象内的属性,添加到 content 字典中
            key = cursor.description[index][0]
            listItem[key] = row[index]
        print(listItem)
        diaryList.append(listItem)
    print(json.dumps(diaryList))
except Exception as err:
    print('error:', err)
finally:
    db.close()

生成的列表

{'id': 1, 'title': '《标题日记》完成输入功能', 'content': None}
{'id': 2, 'title': '睡了一天,有些累,秋天天气真好', 'content': None}
{'id': 3, 'title': '《标题日记》完成同步功能,Yeah!', 'content': None}
{'id': 4, 'title': '玩王者荣耀', 'content': None}
{'id': 5, 'title': '下雨,基本什么也没干', 'content': None}
{'id': 6, 'title': '饥荒口袋,修正 IPv6 连接问题', 'content': None}
{'id': 7, 'title': '昨晚玩游戏玩晚了,今天看电视', 'content': None}
{'id': 8, 'title': '还是118个俯卧撑', 'content': None}
{'id': 9, 'title': '陪哥哥去临朐买石头', 'content': None}
{'id': 10, 'title': '会做西红柿鸡蛋面', 'content': None}

生成的 json

[
  {"id": 1, "title": "\u300a\u6807\u9898\u65e5\u8bb0\u300b\u5b8c\u6210\u8f93\u5165\u529f\u80fd", "content": null}, 
  {"id": 2, "title": "\u7761\u4e86\u4e00\u5929\uff0c\u6709\u4e9b\u7d2f\uff0c\u79cb\u5929\u5929\u6c14\u771f\u597d", "content": null}, 
  {"id": 3, "title": "\u300a\u6807\u9898\u65e5\u8bb0\u300b\u5b8c\u6210\u540c\u6b65\u529f\u80fd\uff0cYeah\uff01", "content": null}, 
  {"id": 4, "title": "\u73a9\u738b\u8005\u8363\u8000", "content": null}, 
  {"id": 5, "title": "\u4e0b\u96e8\uff0c\u57fa\u672c\u4ec0\u4e48\u4e5f\u6ca1\u5e72", "content": null}, 
  {"id": 6, "title": "\u9965\u8352\u53e3\u888b\uff0c\u4fee\u6b63 IPv6 \u8fde\u63a5\u95ee\u9898", "content": null}, 
  {"id": 7, "title": "\u6628\u665a\u73a9\u6e38\u620f\u73a9\u665a\u4e86\uff0c\u4eca\u5929\u770b\u7535\u89c6", "content": null}, 
  {"id": 8, "title": "\u8fd8\u662f118\u4e2a\u4fef\u5367\u6491", "content": null}, 
  {"id": 9, "title": "\u966a\u54e5\u54e5\u53bb\u4e34\u6710\u4e70\u77f3\u5934", "content": null}, 
  {"id": 10, "title": "\u4f1a\u505a\u897f\u7ea2\u67ff\u9e21\u86cb\u9762", "content": null}
]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

十月ooOO

许个愿,我帮你实现

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值