Coverage for src / graphable / parsers / json.py: 100%

24 statements  

« prev     ^ index     » next       coverage.py v7.13.3, created at 2026-02-16 21:32 +0000

1from json import load, loads 

2from logging import getLogger 

3from pathlib import Path 

4from typing import Any 

5 

6from ..graph import Graph 

7from ..registry import register_parser 

8from .utils import build_graph_from_data, is_path 

9 

10logger = getLogger(__name__) 

11 

12 

13@register_parser(".json") 

14def load_graph_json(source: str | Path, reference_type: type = str) -> Graph[Any]: 

15 """ 

16 Load a graph from a JSON string or file. 

17 

18 Args: 

19 source: JSON string or path to a JSON file. 

20 reference_type: The type to cast the node reference to (default: str). 

21 

22 Returns: 

23 Graph: A new Graph instance populated from the JSON data. 

24 """ 

25 if is_path(source): 

26 logger.debug(f"Loading JSON from file: {source}") 

27 with open(source, "r") as f: 

28 data = load(f) 

29 else: 

30 logger.debug("Loading JSON from string.") 

31 data = loads(str(source)) 

32 

33 # Handle wrapped structure: {"checksum": "...", "graph": {"nodes": ..., "edges": ...}} 

34 if "graph" in data and ("nodes" not in data or "edges" not in data): 

35 logger.debug("Detected wrapped JSON structure, extracting 'graph' object.") 

36 data = data["graph"] 

37 

38 nodes_data = data.get("nodes", []) 

39 edges_data = data.get("edges", []) 

40 

41 g = build_graph_from_data(nodes_data, edges_data, reference_type) 

42 logger.info(f"Loaded graph with {len(g)} nodes from JSON.") 

43 return g