目的
python+pandas+PyQt5实现json中某重复名称字段key包含值vlue种类数量
背景
项目测试中碰到格式化后多达1K多行的json串,其中包含了几百个对象,每个对象都有相同的字段结构。统计xxcode字段在整个接口返回中存在多少个value
实现方式
话不多说,直接上代码
import sys
import json
import pandas as pd
from PyQt5.QtWidgets import (QApplication, QWidget, QVBoxLayout, QHBoxLayout,
QTextEdit, QLineEdit, QPushButton, QLabel, QMessageBox)
class CountJsonApp(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
# 创建界面组件
self.json_input = QTextEdit(self)
self.json_input.setPlaceholderText("请输入 JSON 数据")
self.field1_label = QLabel("统计字段 1:", self)
self.field1_input = QLineEdit(self)
self.field2_label = QLabel("统计字段 2:", self)
self.field2_input = QLineEdit(self)
self.submit_button = QPushButton("提交", self)
self.submit_button.clicked.connect(self.process_data)
self.result_text = QTextEdit(self)
self.result_text.setReadOnly(True)
# 布局设置
input_layout = QVBoxLayout()
input_layout.addWidget(QLabel("请输入 JSON 数据:", self))
input_layout.addWidget(self.json_input)
field_layout = QVBoxLayout()
field_layout.addWidget(self.field1_label)
field_layout.addWidget(self.field1_input)
field_layout.addWidget(self.field2_label)
field_layout.addWidget(self.field2_input)
button_layout = QHBoxLayout()
button_layout.addWidget(self.submit_button)
result_layout = QVBoxLayout()
result_layout.addWidget(QLabel("结果:", self))
result_layout.addWidget(self.result_text)
main_layout = QVBoxLayout()
main_layout.addLayout(input_layout)
main_layout.addLayout(field_layout)
main_layout.addLayout(button_layout)
main_layout.addLayout(result_layout)
self.setLayout(main_layout)
self.setWindowTitle('统计 JSON 中字段对应值的种类')
self.setGeometry(300, 300, 800, 600)
self.show()
def process_data(self):
data = self.json_input.toPlainText()
count1 = self.field1_input.text()
count2 = self.field2_input.text()
try:
# 将 JSON 字符串转换为 Python 对象
json_data = json.loads(data)
# 将 JSON 数据转换为 DataFrame
df = pd.json_normalize(json_data)
# 统计字段 1 不同值的数量
unique_count1 = df[count1].nunique()
result = f"{count1} 字段不同值的数量: {unique_count1}"
if count2:
# 统计字段 2 不同值的数量
unique_count2 = df[count2].nunique()
result += f"\n{count2} 字段不同值的数量: {unique_count2}"
# 格式化输入的 JSON 数据
formatted_json = json.dumps(json_data, indent=4, ensure_ascii=False)
result += f"\n\n格式化后的 JSON 数据:\n{formatted_json}"
self.result_text.setPlainText(result)
except json.JSONDecodeError as e:
QMessageBox.critical(self, "错误", f"处理数据时出错,JSON 解析失败,错误位置:第 {e.lineno} 行第 {e.colno} 列 (字符索引 {e.pos}),错误信息:{e.msg}")
except Exception as e:
QMessageBox.critical(self, "错误", f"处理数据时出错: {str(e)}")
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = CountJsonApp()
sys.exit(app.exec_())
打包exe方法
1. 安装依赖库
运行以下命令安装所需的库:
pip install pyinstaller pyqt5 pandas
2.使用 PyInstaller 打包
在命令行中,进入 该py文件所在的目录,执行以下命令:
pyinstaller --onefile --name 执行文件名 py文件名.py
3.运行可执行文件
打包完成后,在 dist 目录下会生成 xxxx.exe 文件。双击该文件即可运行图形化界面的应用程序效果展示