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}
]

python pymysql 如何输出 json 字符串相关推荐

  1. java调用python,传参json字符串,含中文传参

    java调用python,传参json字符串 python脚本内容(test.py) # -*- coding: utf-8 -*-def main(input):return input java调 ...

  2. linux命令下jq的用法(curl 格式化输出json 字符串)

    文章目录 一.什么是jq命令 1. jq安装 2. jq命令的格式 从json文件 对象数组中取出一组特定的属性的值 从json文件 对象数组中取出一组特定的属性的值,并排除null值 格式化输出js ...

  3. JAVA-Gson-格式化输出json字符串

    使用Gson格式化输出json字符串 POM <dependency><groupId>com.google.code.gson</groupId><arti ...

  4. python模块list 转json字符串_python 列表 字典转json

    一.Dictionary 转为JSON 将dict转为JSON,这里利用包json import json aItem = {} aItem["id"] = "2203& ...

  5. Python 对象数组 转JSON 字符串

    前言 在Python中基本数据类型可以直接使用json.dumps直接转json字符串,但是对于自定义的类来说,需要先将对象"字典化",也就是使用__dict__这个函数:同理对于 ...

  6. python字符数组输出_python字符串格式化输出

    字符串格式化输出 : 字符串的拼接第一种方式 如:name = input("name:") age = input("age:") job = input(& ...

  7. python控制台颜色输出以及字符串格式化输出

    2019独角兽企业重金招聘Python工程师标准>>> 显示颜色格式:\033[显示方式;字体色;背景色m......[\033[0m] ---------------------- ...

  8. python语言格式化输出_Python字符串格式化输出

    原博文 2019-11-22 12:48 − 本文链接:https://www.cnblogs.com/zyuanlbj/p/11910913.html 使用占位符%s name = '小飞' pri ...

  9. excel巧用拼接函数CONCATENATE输出JSON字符串

    使用 CONCATENATE(其中一个文本函数)将两个或多个文本字符串联接为一个字符串. 在 Excel 2016.Excel Mobile 和 Excel 网页版 中,此函数已替换为 CONCAT ...

最新文章

  1. POJ 2778 DNA Sequence —— (AC自动机+矩阵快速幂)
  2. go语言笔记——map map 默认是无序的,不管是按照 key 还是按照 value 默认都不排序...
  3. angularJS(5)
  4. 【网络知识】1. 路由器或网桥的2.4G和5G的Wi-Fi各自优缺点对比
  5. 自定义控件只允许输入Decimal和int类型字符串
  6. 一步步学习SPD2010--附录C--使用SP2010管理任务(6)--配置外部内容类型配置文件页面宿主...
  7. 开发中的坑:MQ 也能做 RPC 调用?
  8. CTR深度学习模型之 DIN(Deep Interest Network) 的理解与例子
  9. java基础之HashTable和HashMap的区别
  10. ioctl之FIONREAD
  11. leetcode933. 最近的请求次数
  12. VS2019-C++警告-C6385读取数据无效
  13. JWT(JSON Web Token)的基本原理
  14. 普通机器学习模型的提升
  15. Problem 71:Ordered fractions
  16. 三角形各种心的代数几何性质
  17. 2021年中国电动自行车行业现状分析:产业特征明显,“新国标”促使行业发展更加规范化[图]
  18. 一文学会快速傅里叶变换(FFT)
  19. python入门笔记——类和对象③(案例:自动随机文字游戏——决战紫禁之巅)
  20. kafka-集群搭建

热门文章

  1. nrf52832 TWI/I2C 调试
  2. 【讨论课2】学校里面针对一些高大树木进行处理,处理措施如下:(1)高度大于50米的树木,采用“巨型升降机”砍伐,将其截成11节;(2)高度在40米到50米之间的树木,采用“巨型升降机”砍伐,每5米将其
  3. box-sizing: border-box;的作用
  4. matlab相机标定Options选项解析
  5. MarkDown语法1:Typora
  6. 在 Visual Studio Code 中添加自定义的代码片段
  7. 《哪吒》将在北美上映,网友问:我命由我不由天该怎么翻译?
  8. 二手手机回收领域新趋势
  9. 用CSS实现三角形及其原理
  10. 《奔跑吧Linux内核》开始预售啦