Skip to content

Commit

Permalink
Make pyjsonviewer callable from python. (#39)
Browse files Browse the repository at this point in the history
* add support for list data. #31

* add test cases.

* add test for nested json.

* list under second layer should be expanded as trees. #35

* limit list view to MAX_N_SHOW_ITEM

* avoid naming conflict.

* refactor main file.

* expose function view_data from pyjsonviewer.

* update readme file to show python usage.

* Update pyjsonviewer.py

* refactor main file.

* expose function view_data from pyjsonviewer.

* update readme file to show python usage.

* refactor main file.

* expose function view_data from pyjsonviewer.

* update readme file to show python usage.

* Code review changes.

#39 (comment)
  • Loading branch information
Ankush-Chander authored May 8, 2021
1 parent dccd11e commit 413eee4
Show file tree
Hide file tree
Showing 4 changed files with 59 additions and 24 deletions.
19 changes: 19 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,25 @@ You can set initial directory:

- Show release note: Help -> Release note

## Inside python code

### View json file
```
import pyjsonviewer
pyjsonviewer.view_data(json_file="dat/list.json")
```
JSON data tree will be shown.

### View json object
```
import pyjsonviewer
json_object = {"a":[1,2,3], "b":"test"}
pyjsonviewer.view_data(json_data=json_object)
```
JSON data tree will be shown.

## Vimrc setting

If you are a vim user, you can set this command in your vimrc.
Expand Down
1 change: 1 addition & 0 deletions pyjsonviewer/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
from .pyjsonviewer import view_data
62 changes: 38 additions & 24 deletions pyjsonviewer/pyjsonviewer.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ def auto_width(self, max_width):
break
self.config(width=width + w)

def __init__(self, master, json_path=None, initial_dir="~/"):
def __init__(self, master, json_path=None, json_data=None, initial_dir="~/"):
super().__init__(master)
self.master = master
self.tree = ttk.Treeview(self)
Expand All @@ -68,7 +68,9 @@ def __init__(self, master, json_path=None, initial_dir="~/"):
self.search_label = None

if json_path:
self.set_table_data_from_json(json_path)
self.set_table_data_from_json_path(json_path)
elif json_data:
self.set_table_data_from_json(json_data)

def create_widgets(self):
self.tree.bind('<Double-1>', self.click_item)
Expand Down Expand Up @@ -127,7 +129,7 @@ def select_json_file(self, event=None):
file_path = filedialog.askopenfilename(
initialdir=self.initial_dir,
filetypes=FILETYPES)
self.set_table_data_from_json(file_path)
self.set_table_data_from_json_path(file_path)

def expand_all(self, event=None):
"""
Expand Down Expand Up @@ -181,7 +183,7 @@ def select_listbox_item(self, event):
w = event.widget
index = int(w.curselection()[0])
value = w.get(index)
self.set_table_data_from_json(value)
self.set_table_data_from_json_path(value)
self.sub_win.destroy() # close window

def select_json_file_from_history(self, event=None):
Expand Down Expand Up @@ -214,11 +216,15 @@ def save_json_history(self, file_path):
for line in lines:
f.write(line.replace("\n", "") + "\n")

def set_table_data_from_json(self, file_path):
def set_table_data_from_json(self, json_data):
assert type(json_data) in (list, dict)
self.delete_all_nodes()
self.insert_nodes(json_data)

def set_table_data_from_json_path(self, file_path):
data = self.load_json_data(file_path)
self.save_json_history(file_path)
self.delete_all_nodes()
self.insert_nodes(data)
self.set_table_data_from_json(data)

def delete_all_nodes(self):
for i in self.tree.get_children():
Expand Down Expand Up @@ -277,30 +283,20 @@ def show_info_window():
messagebox.showinfo("About", msg)


def main():
print(__file__ + " start!!")

parser = argparse.ArgumentParser()
parser.add_argument('-f', '--file', type=str, help='JSON file path')
parser.add_argument('-d', '--dir', type=str,
help='JSON file directory')
parser.add_argument('-o', '--open', action='store_true',
default=False, help='Open with finder')
args = parser.parse_args()

def view_data(json_file=None, json_data=None, initial_dir=None):
root: Tk = tk.Tk()
root.title('PyJSONViewer')
root.geometry("500x500")
root.tk.call('wm', 'iconphoto', root._w,
tk.PhotoImage(file=PROJECT_DIR + '/icon.png'))
menubar = tk.Menu(root)

if args.open:
args.file = filedialog.askopenfilename(
initialdir=args.dir,
filetypes=FILETYPES)

app = JSONTreeFrame(root, json_path=args.file, initial_dir=args.dir)
if json_file:
app = JSONTreeFrame(root, json_path=json_file, initial_dir=initial_dir)
elif json_data:
app = JSONTreeFrame(root, json_data=json_data)
else:
app = JSONTreeFrame(root)

file_menu = tk.Menu(menubar, tearoff=0)
file_menu.add_command(label="Open", accelerator='Ctrl+O',
Expand Down Expand Up @@ -340,5 +336,23 @@ def main():
root.mainloop()


def main():
print(__file__ + " start!!")

parser = argparse.ArgumentParser()
parser.add_argument('-f', '--file', type=str, help='JSON file path')
parser.add_argument('-d', '--dir', type=str,
help='JSON file directory')
parser.add_argument('-o', '--open', action='store_true',
default=False, help='Open with finder')
args = parser.parse_args()

if args.open:
args.file = filedialog.askopenfilename(
initialdir=args.dir,
filetypes=FILETYPES)
view_data(json_file=args.file, initial_dir=args.dir)


if __name__ == '__main__':
main()
1 change: 1 addition & 0 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@
keywords="python json tkinter",
packages=find_packages(),
include_package_data=True,
py_modules=["pyjsonviewer"],
entry_points={
'console_scripts': ['pyjsonviewer=pyjsonviewer.pyjsonviewer:main']},
classifiers=[
Expand Down

0 comments on commit 413eee4

Please sign in to comment.