Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/).

### Added
- Added `parser_factory` argument to `Markdown` and `MarkdownViewer` constructors https://github.com/Textualize/textual/pull/2075
- Added the option to supply a custom path in the `json_tree.py` example https://github.com/Textualize/textual/pull/2087

### Changed

Expand Down
19 changes: 12 additions & 7 deletions examples/json_tree.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import json
from sys import argv
from pathlib import Path
from typing import Optional

from rich.text import Text

Expand All @@ -16,6 +18,10 @@ class TreeApp(App):
("t", "toggle_root", "Toggle root"),
]

def __init__(self, json_path: Optional[Path] = None, *args, **kwargs):
self.json_path = json_path or Path(__file__).parent / "food.json"
super().__init__(*args, **kwargs)

def compose(self) -> ComposeResult:
yield Header()
yield Footer()
Expand Down Expand Up @@ -43,31 +49,30 @@ def add_node(name: str, node: TreeNode, data: object) -> None:
data (object): Data associated with the node.
"""
if isinstance(data, dict):
node._label = Text(f"{{}} {name}")
node.set_label(Text(f"{{}} {name}"))
for key, value in data.items():
new_node = node.add("")
add_node(key, new_node, value)
elif isinstance(data, list):
node._label = Text(f"[] {name}")
node.set_label(Text(f"[] {name}"))
for index, value in enumerate(data):
new_node = node.add("")
add_node(str(index), new_node, value)
else:
node._allow_expand = False
node.allow_expand = False
if name:
label = Text.assemble(
Text.from_markup(f"[b]{name}[/b]="), highlighter(repr(data))
)
else:
label = Text(repr(data))
node._label = label
node.set_label(label)

add_node("JSON", node, json_data)

def on_mount(self) -> None:
"""Load some JSON when the app starts."""
file_path = Path(__file__).parent / "food.json"
with open(file_path) as data_file:
with open(self.json_path) as data_file:
self.json_data = json.load(data_file)

def action_add(self) -> None:
Expand All @@ -89,5 +94,5 @@ def action_toggle_root(self) -> None:


if __name__ == "__main__":
app = TreeApp()
app = TreeApp(json_path=Path(argv[1]) if len(argv) >= 2 else None)
app.run()