Skip to content

JSON

Functions for working with JSON data.


DecimalEncoder

Bases: JSONEncoder

Used to encode decimal.Decimal when printing/encoding dicts to JSON strings

default

default(o)

Encode decimal.Decimal values as strings.

Parameters:

Name Type Description Default
o Any

The object to encode.

required

Returns:

Type Description
str | JSONEncoder

String representation for Decimal values, otherwise delegates to parent.

Source code in src/aibs_informatics_core/utils/json.py
26
27
28
29
30
31
32
33
34
35
36
37
def default(self, o: Any) -> str | json.JSONEncoder:
    """Encode ``decimal.Decimal`` values as strings.

    Args:
        o: The object to encode.

    Returns:
        String representation for Decimal values, otherwise delegates to parent.
    """
    if isinstance(o, decimal.Decimal):
        return str(o)
    return super().default(o)

is_json_str

is_json_str(data)

Check if a value is a valid JSON string.

Parameters:

Name Type Description Default
data Any

The value to check.

required

Returns:

Type Description
bool

True if data is a string containing valid JSON.

Source code in src/aibs_informatics_core/utils/json.py
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
def is_json_str(data: Any) -> bool:
    """Check if a value is a valid JSON string.

    Args:
        data: The value to check.

    Returns:
        True if ``data`` is a string containing valid JSON.
    """
    try:
        assert isinstance(data, str)
        json.loads(data)
    except Exception:
        return False
    return True

load_json

load_json(path_or_str, **kwargs)

Load JSON from a string or file path.

Parameters:

Name Type Description Default
path_or_str str | Path

A JSON string or path to a JSON file.

required
**kwargs

Additional keyword arguments passed to json.loads or json.load.

{}

Returns:

Type Description
JSON

The parsed JSON value.

Raises:

Type Description
ValueError

If the input is neither a valid JSON string nor an existing file path.

Source code in src/aibs_informatics_core/utils/json.py
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
def load_json(path_or_str: str | Path, **kwargs) -> JSON:
    """Load JSON from a string or file path.

    Args:
        path_or_str: A JSON string or path to a JSON file.
        **kwargs: Additional keyword arguments passed to ``json.loads`` or ``json.load``.

    Returns:
        The parsed JSON value.

    Raises:
        ValueError: If the input is neither a valid JSON string nor an existing file path.
    """
    if isinstance(path_or_str, str) and is_json_str(path_or_str):
        return json.loads(path_or_str, **kwargs)
    elif Path(path_or_str).exists():
        with open(str(path_or_str)) as f:
            return json.load(f, **kwargs)
    else:
        raise ValueError(f"Cannot load {path_or_str} as json. Not valid json string or path.")

load_json_object

load_json_object(path_or_str, **kwargs)

Load a JSON object (dict) from a string or file path.

Parameters:

Name Type Description Default
path_or_str str | Path

A JSON string or path to a JSON file.

required
**kwargs

Additional keyword arguments passed to load_json.

{}

Returns:

Type Description
dict[str, JSON]

The parsed JSON object as a dictionary.

Raises:

Type Description
ValueError

If the loaded JSON is not a dictionary.

Source code in src/aibs_informatics_core/utils/json.py
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
def load_json_object(path_or_str: str | Path, **kwargs) -> dict[str, JSON]:
    """Load a JSON object (dict) from a string or file path.

    Args:
        path_or_str: A JSON string or path to a JSON file.
        **kwargs: Additional keyword arguments passed to ``load_json``.

    Returns:
        The parsed JSON object as a dictionary.

    Raises:
        ValueError: If the loaded JSON is not a dictionary.
    """
    json_data = load_json(path_or_str, **kwargs)
    if not isinstance(json_data, dict):
        raise ValueError(f"{path_or_str} was loaded as JSON but not a JSON Object")
    return cast(dict[str, JSON], json_data)