Coverage for C: \ Users \ peaco \ OneDrive \ Documents \ GitHub \ mth5 \ mth5 \ io \ phoenix \ readers \ helpers.py: 100%

8 statements  

« prev     ^ index     » next       coverage.py v7.13.1, created at 2026-01-10 00:01 -0800

1# -*- coding: utf-8 -*- 

2""" 

3Helper utilities for Phoenix Geophysics reader module. 

4 

5Created on Tue Jun 20 15:51:20 2023 

6 

7@author: jpeacock 

8""" 

9 

10from __future__ import annotations 

11 

12# ============================================================================= 

13# Imports 

14# ============================================================================= 

15import json 

16from types import SimpleNamespace 

17from typing import TYPE_CHECKING 

18 

19 

20if TYPE_CHECKING: 

21 from pathlib import Path 

22 

23 

24# ============================================================================= 

25 

26 

27def read_json_to_object(fn: str | Path) -> SimpleNamespace: 

28 """ 

29 Read a JSON file directly into a SimpleNamespace object. 

30 

31 Parameters 

32 ---------- 

33 fn : str or Path 

34 Path to the JSON file to read. 

35 

36 Returns 

37 ------- 

38 SimpleNamespace 

39 Object containing the JSON data as attributes. 

40 

41 Raises 

42 ------ 

43 FileNotFoundError 

44 If the specified file does not exist. 

45 json.JSONDecodeError 

46 If the file contains invalid JSON. 

47 IOError 

48 If there's an error reading the file. 

49 

50 Examples 

51 -------- 

52 >>> obj = read_json_to_object("config.json") 

53 >>> print(obj.some_attribute) 

54 

55 Notes 

56 ----- 

57 This function uses json.load with an object_hook to convert 

58 all dictionaries to SimpleNamespace objects, allowing dot 

59 notation access to nested JSON properties. 

60 """ 

61 with open(fn, "r") as fid: 

62 obj = json.load(fid, object_hook=lambda d: SimpleNamespace(**d)) 

63 return obj