Warning: Can not open [/home/conf/public_html/cgi-bin/show_python.log]. Ignore No title

Download script from JSONView.py
Related files:


import os
import sys
import toml
import tkinter as tk
from tkinter import ttk
import json


if len(sys.argv) <= 1:
    print("Usage: python xml_viewer.py infile window_size")
    sys.exit(1)


inifile = os.path.splitext(sys.argv[0])[0] + ".ini"
if os.path.isfile(inifile):
    geometry = toml.load(inifile).get("geometry", geometry)

nargs = len(sys.argv)
if nargs >= 2:
    infile = sys.argv[1]
if nargs >= 3:
    geometry = sys.argv[2]

def load_json(filename):
    with open(filename, "r") as file:
        return json.load(file)

def insert_item(tree, parent, key, value):
    if isinstance(value, dict):
        node = tree.insert(parent, 'end', text=str(key), open=False)
        for subkey, subvalue in value.items():
            insert_item(tree, node, subkey, subvalue)
    elif isinstance(value, list):
        node = tree.insert(parent, 'end', text=str(key) + '[]', open=False)
        for i, item in enumerate(value):
            insert_item(tree, node, f'Item {i}', item)
    else:
        tree.insert(parent, 'end', text=str(key), value=str(value))

def build_tree(tree, data):
    tree["columns"] = ("one",)
    tree.column("#0", width=270, minwidth=270, stretch=tk.NO)
    tree.column("one", width=150, minwidth=150, stretch=tk.NO)

    tree.heading("#0", text="Key", anchor=tk.W)
    tree.heading("one", text="Value", anchor=tk.W)

    for key, value in data.items():
        insert_item(tree, '', key, value)

def window_close(root):
    with open(inifile, "w") as file:
        toml.dump({"geometry": root.geometry()}, file)
    root.quit()

def main(infile, geometry):
    root = tk.Tk()
    root.title(f"JSON Viewer - {infile}")
    root.geometry(geometry)
    root.protocol("WM_DELETE_WINDOW", lambda: window_close(root))

    tree = ttk.Treeview(root)
    data = load_json(infile)
    build_tree(tree, data)
    tree.pack(side='top', fill='both', expand=True)

    root.mainloop()

if __name__ == "__main__":
    main(infile, geometry)