Skip to content

capturegraph.data.save.savers #

PType Saver Registry#

Maps Python types to saver functions that convert them back to JSON format compatible with the CaptureGraph iOS app.

Example
import capturegraph.data as cg

cg.typed_json.encode(True)           # → {"bool": True}
cg.typed_json.encode(42.5)           # → {"number": 42.5, "is_time_interval": False}
cg.typed_json.encode(location)       # → {"latitude": ..., "longitude": ..., ...}

save_to_json(value) #

Convert a Python value to its PType JSON representation.

Parameters:

Name Type Description Default
value Any

The value to convert. Must be a registered type or have a to_json() method.

required

Returns:

Type Description
dict

JSON-serializable dict in the appropriate PType format.

Raises:

Type Description
TypeError

If the value type is not supported.

Example
import capturegraph.data as cg

cg.typed_json.encode(True)  # {'bool': True}
cg.typed_json.encode(42.5)  # {'number': 42.5, 'is_time_interval': False}
Source code in capturegraph-lib/capturegraph/data/save/savers.py
def save_to_json(value: Any) -> dict:
    """Convert a Python value to its PType JSON representation.

    Args:
        value: The value to convert. Must be a registered type or
               have a to_json() method.

    Returns:
        JSON-serializable dict in the appropriate PType format.

    Raises:
        TypeError: If the value type is not supported.

    Example:
        ```python
        import capturegraph.data as cg

        cg.typed_json.encode(True)  # {'bool': True}
        cg.typed_json.encode(42.5)  # {'number': 42.5, 'is_time_interval': False}
        ```
    """
    value_type = type(value)

    if value_type in PTYPE_SAVERS:
        return PTYPE_SAVERS[value_type](value)

    elif isinstance(value, dict):
        if hasattr(type(value), "to_dict"):
            return value.to_dict()
        return dict(value)
    elif isinstance(value, list):
        return list(value)
    elif hasattr(value, "to_json"):
        return value.to_json()
    elif hasattr(value, "to_dict"):
        return value.to_dict()
    else:
        raise TypeError(
            f"Cannot save value of type {value_type.__name__}. "
            f"Register a saver in PTYPE_SAVERS or add a to_json() method."
        )