Skip to content

serializefilters

Class info

🛈 DocStrings

deserialize

deserialize(data: str, fmt: SerializeFormatStr, **kwargs: Any) -> Any

Serialize given json-like object to given format.

Parameters:

Name Type Description Default
data str

The data to deserialize

required
fmt SerializeFormatStr

The serialization format

required
kwargs Any

Keyword arguments passed to the loader function

{}
Source code in src/jinjarope/serializefilters.py
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
def deserialize(data: str, fmt: SerializeFormatStr, **kwargs: Any) -> Any:
    """Serialize given json-like object to given format.

    Args:
        data: The data to deserialize
        fmt: The serialization format
        kwargs: Keyword arguments passed to the loader function
    """
    match fmt:
        case "yaml":
            import yamling

            return yamling.load_yaml(data, **kwargs)
        case "json":
            return json.loads(data, **kwargs)
        case "ini":
            return load_ini(data, **kwargs)
        case "toml":
            import tomllib

            return tomllib.loads(data, **kwargs)
        case _:
            raise TypeError(fmt)

dig

dig(
    data: dict, *sections: str, keep_path: bool = False, dig_yaml_lists: bool = True
) -> Any

Try to get data with given section path from a dict-list structure.

If a list is encountered and dig_yaml_lists is true, treat it like a list of {"identifier", {subdict}} items, as used in MkDocs config for plugins & extensions. If Key path does not exist, return None.

Parameters:

Name Type Description Default
data dict

The data to dig into

required
sections str

Sections to dig into

()
keep_path bool

Return result with original nesting

False
dig_yaml_lists bool

Also dig into single-key->value pairs, as often found in yaml.

True
Source code in src/jinjarope/serializefilters.py
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
def dig(
    data: dict,
    *sections: str,
    keep_path: bool = False,
    dig_yaml_lists: bool = True,
) -> Any:
    """Try to get data with given section path from a dict-list structure.

    If a list is encountered and dig_yaml_lists is true, treat it like a list of
    {"identifier", {subdict}} items, as used in MkDocs config for
    plugins & extensions.
    If Key path does not exist, return None.

    Args:
        data: The data to dig into
        sections: Sections to dig into
        keep_path: Return result with original nesting
        dig_yaml_lists: Also dig into single-key->value pairs, as often found in yaml.
    """
    for i in sections:
        if isinstance(data, dict):
            if child := data.get(i):
                data = child
            else:
                return None
        elif dig_yaml_lists and isinstance(data, list):
            # this part is for yaml-style listitems
            for idx in data:
                if i in idx and isinstance(idx, dict):
                    data = idx[i]
                    break
                if isinstance(idx, str) and idx == i:
                    data = idx
                    break
            else:
                return None
    if not keep_path:
        return data
    result: dict[str, dict] = {}
    new = result
    for sect in sections:
        result[sect] = data if sect == sections[-1] else {}
        result = result[sect]
    return new

merge

merge(
    target: list | dict,
    *source: list | dict,
    deepcopy: bool = False,
    mergers: dict[type, Callable[[Any, Any, Any], Any]] | None = None
) -> list | dict

Merge given data structures using mergers provided.

Parameters:

Name Type Description Default
target list | dict

Data structure to merge into

required
source list | dict

Data structures to merge into target

()
deepcopy bool

Whether to deepcopy the target

False
mergers dict[type, Callable[[Any, Any, Any], Any]] | None

Mergers with strategies for each type (default: additive)

None
Source code in src/jinjarope/serializefilters.py
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
def merge(
    target: list | dict,
    *source: list | dict,
    deepcopy: bool = False,
    mergers: dict[type, Callable[[Any, Any, Any], Any]] | None = None,
) -> list | dict:
    """Merge given data structures using mergers provided.

    Args:
        target: Data structure to merge into
        source:  Data structures to merge into target
        deepcopy: Whether to deepcopy the target
        mergers: Mergers with strategies for each type (default: additive)
    """
    import copy

    if deepcopy:
        target = copy.deepcopy(target)
    context = deepmerge.DeepMerger(mergers)
    for s in source:
        target = context.merge(s, target)
    return target

serialize

serialize(data: Any, fmt: SerializeFormatStr, **kwargs: Any) -> str

Serialize given json-like object to given format.

Parameters:

Name Type Description Default
data Any

The data to serialize

required
fmt SerializeFormatStr

The serialization format

required
kwargs Any

Keyword arguments passed to the dumper function

{}
Source code in src/jinjarope/serializefilters.py
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
def serialize(data: Any, fmt: SerializeFormatStr, **kwargs: Any) -> str:
    """Serialize given json-like object to given format.

    Args:
        data: The data to serialize
        fmt: The serialization format
        kwargs: Keyword arguments passed to the dumper function
    """
    match fmt:
        case "yaml":
            import yamling

            return yamling.dump_yaml(data, **kwargs)
        case "json":
            return json.dumps(data, indent=4, **kwargs)
        case "ini":
            config = configparser.ConfigParser(**kwargs)
            config.read_dict(data)
            file = io.StringIO()
            with file as fp:
                config.write(fp)
                return file.getvalue()
        case "toml" if isinstance(data, dict):
            import tomli_w

            return tomli_w.dumps(data, **kwargs)
        case _:
            raise TypeError(fmt)