Coverage for src / check_datapackage / read_json.py: 100%

11 statements  

« prev     ^ index     » next       coverage.py v7.13.5, created at 2026-04-09 12:26 +0000

1from json import JSONDecodeError, loads 

2from pathlib import Path 

3from typing import Any, cast 

4 

5 

6def read_json(path: Path) -> dict[str, Any]: 

7 """Reads `datapackage.json` into a Python dictionary. 

8 

9 Args: 

10 path: The path to the `datapackage.json` file to read. 

11 

12 Returns: 

13 The contents of the JSON file as a Python dictionary. 

14 

15 Raises: 

16 FileNotFoundError: If the file does not exist. 

17 JSONDecodeError: If the contents of the file cannot be de-serialised as JSON. 

18 TypeError: If the contents of the JSON file aren't converted to a Python 

19 dictionary. 

20 """ 

21 try: 

22 properties: Any = loads(path.read_text()) 

23 except JSONDecodeError as error: 

24 raise JSONDecodeError( 

25 f"The path {path} couldn't be parsed as JSON. Is there a typo or other " 

26 "issue in the file?", 

27 doc=error.doc, 

28 pos=error.pos, 

29 ) from None # To hide the original traceback 

30 

31 if not isinstance(properties, dict): 

32 raise TypeError( 

33 f"The file {path} should parse into a Python dictionary (`dict`) " 

34 f"but it converts to the type `{type(properties)}`. Is the file " 

35 "missing a curly bracket `{` at the beginning or `}` at the end?" 

36 ) from None # To hide the original traceback 

37 

38 return cast(dict[str, Any], properties)