import json
import tkinter as tk
def json_compress(json_str):
try:
json_obj = json.loads(json_str)
except Exception as e:
print(e)
return ""
else:
return json.dumps(json_obj, separators=(",", ":"))
def json_format(json_str):
try:
json_obj = json.loads(json_str)
except Exception as e:
print(e)
return ""
else:
return json.dumps(json_obj, indent=4)
class GUI(tk.Frame):
def __init__(self, master):
super().__init__(master)
master.title("JSON压缩和格式化工具")
master.geometry("800x600")
self.text = tk.Text(self)
self.compress_button = tk.Button(
self, text="压缩", command=self.compress)
self.format_button = tk.Button(self, text="格式化", command=self.format)
self.text.pack(fill=tk.BOTH, expand=True)
self.compress_button.pack(side=tk.LEFT)
self.format_button.pack(side=tk.RIGHT)
def compress(self):
json_str = self.text.get(1.0, tk.END)
compressed_str = json_compress(json_str)
self.text.delete(1.0, tk.END)
self.text.insert(1.0, compressed_str)
def format(self):
json_str = self.text.get(1.0, tk.END)
formatted_str = json_format(json_str)
self.text.delete(1.0, tk.END)
self.text.insert(1.0, formatted_str)
root = tk.Tk()
app = GUI(root)
app.pack(fill=tk.BOTH, expand=True)
root.mainloop()