Parser Examples

The following script shows how to load graphs from various machine-readable formats including JSON, YAML, and CSV.

This script (available as examples/parser_examples.py) shows how to: - Load graphs from JSON files and strings. - Load graphs from YAML. - Load graphs from CSV edge lists.

Command

uv run examples/parser_examples.py > docs/_static/examples/parser_examples_output.txt

Script

examples/parser_examples.py
 1from graphable.graph import Graph
 2from graphable.views.texttree import create_topology_tree_txt
 3
 4
 5def demo_json_parsing():
 6    print("\n--- JSON Parsing ---")
 7    json_data = """
 8    {
 9      "nodes": [{"id": "A"}, {"id": "B"}],
10      "edges": [{"source": "A", "target": "B", "label": "depends"}]
11    }
12    """
13    g = Graph.from_json(json_data)
14    print(f"Loaded {len(g)} nodes from JSON string.")
15    print(g.render(create_topology_tree_txt))
16
17
18def demo_yaml_parsing():
19    print("\n--- YAML Parsing ---")
20    yaml_data = """
21nodes:
22  - id: Server
23  - id: Client
24edges:
25  - source: Server
26    target: Client
27    """
28    g = Graph.from_yaml(yaml_data)
29    print(f"Loaded {len(g)} nodes from YAML string.")
30    print(g.render(create_topology_tree_txt))
31
32
33def demo_toml_parsing():
34    print("\n--- TOML Parsing ---")
35    toml_data = """
36[[nodes]]
37id = "App"
38[[nodes]]
39id = "DB"
40
41[[edges]]
42source = "DB"
43target = "App"
44"""
45    g = Graph.from_toml(toml_data)
46    print(f"Loaded {len(g)} nodes from TOML string.")
47    print(g.render(create_topology_tree_txt))
48
49
50def demo_csv_parsing():
51    print("\n--- CSV Parsing ---")
52    csv_data = "source,target\nNode1,Node2\nNode2,Node3"
53    g = Graph.from_csv(csv_data)
54    print(f"Loaded {len(g)} nodes from CSV string.")
55    print(g.render(create_topology_tree_txt))
56
57
58def main():
59    print("Graphable Parser Examples\n")
60    demo_json_parsing()
61    demo_yaml_parsing()
62    demo_toml_parsing()
63    demo_csv_parsing()
64
65
66if __name__ == "__main__":
67    main()

Output

Running the script produces the following text output: