Python如何实现打印JSON格式数据时每个键值对单独占一行
解决方案
首先你原有代码里存在一个多余的错误操作:jsonStr = json.dumps(qrData),qrData本身是解码后的JSON字符串,直接传给json.loads即可解析为Python对象,对字符串类型的JSON内容调用dumps会导致内容被二次转义,属于无效操作。
方案1:使用json.dumps内置格式化参数(推荐,实现最简单)
不需要手动遍历键值对,json.dumps自带格式化输出参数,直接配置即可实现多层级自动换行、缩进:
indent:设置缩进空格数,会自动按JSON结构层级换行ensure_ascii=False:如果内容包含中文等非ASCII字符,加这个参数避免输出乱码sort_keys=True(可选):可以按key的字母顺序排序输出
修改后的代码示例:
import json qrData = qr.data.decode("utf-8") qrType = qr.type # 解析为Python对象 json_object = json.loads(qrData) # 生成格式化的JSON字符串 formatted_json = json.dumps(json_object, indent=2, ensure_ascii=False) print("[INFORMATION] Found {} barcode:\n{}".format(qrType, formatted_json))
输出效果参考:
[INFORMATION] Found QRCODE barcode: { "version": 1, "insured": { "firstname": "XX", "lastname": "XXT" }, "vehicle": { "brand": "LEXUS", "type": "NX", "licensePlate": "ABCDED", "country": "XX" }, "insurer": { "id": "data" } }
方案2:自定义递归遍历(适合需要纯键值对无JSON符号的场景)
如果你不想要JSON的大括号、引号,希望纯输出层级化的键值对,可以写递归函数处理:
import json def print_nested_dict(d, indent=0): for key, value in d.items(): # 按层级加缩进 print(" " * indent + "{}: ".format(key), end="") if isinstance(value, dict): # 值为字典则换行递归 print() print_nested_dict(value, indent + 1) else: # 普通值直接输出 print(value) # 业务代码 qrData = qr.data.decode("utf-8") qrType = qr.type json_object = json.loads(qrData) print("[INFORMATION] Found {} barcode:".format(qrType)) print_nested_dict(json_object)
输出效果参考:
[INFORMATION] Found QRCODE barcode: version: 1 insured: firstname: XX lastname: XXT vehicle: brand: LEXUS type: NX licensePlate: ABCDED country: XX insurer: id: data
内容的提问来源于stack exchange,提问作者Kwinten
相关产品推荐
相关产品推荐

