Skip to content

jsonbourne

jsonbourne.core.JsonModule() ⚓︎

JSON class meant to mimic the js/ts-JSON

Source code in libs/jsonbourne/jsonbourne/core.py
1167
def __init__(self) -> None: ...

Functions⚓︎

jsonbourne.core.JsonModule.binify(data: Any, fmt: bool = False, pretty: bool = False, sort_keys: bool = False, append_newline: bool = False, default: Optional[Callable[[Any], Any]] = None, **kwargs: Any) -> bytes staticmethod ⚓︎

Return JSON string bytes for given data

Source code in libs/jsonbourne/jsonbourne/core.py
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
@staticmethod
def binify(
    data: Any,
    fmt: bool = False,
    pretty: bool = False,
    sort_keys: bool = False,
    append_newline: bool = False,
    default: Optional[Callable[[Any], Any]] = None,
    **kwargs: Any,
) -> bytes:
    """Return JSON string bytes for given data"""
    return bytes(
        jsonlib.dumpb(
            data,
            fmt=fmt,
            pretty=pretty,
            sort_keys=sort_keys,
            append_newline=append_newline,
            default=default,
            **kwargs,
        )
    )

jsonbourne.core.JsonModule.dumpb(data: Any, fmt: bool = False, pretty: bool = False, sort_keys: bool = False, append_newline: bool = False, default: Optional[Callable[[Any], Any]] = None, **kwargs: Any) -> bytes staticmethod ⚓︎

Return JSON string bytes for given data

Source code in libs/jsonbourne/jsonbourne/core.py
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
@staticmethod
def dumpb(
    data: Any,
    fmt: bool = False,
    pretty: bool = False,
    sort_keys: bool = False,
    append_newline: bool = False,
    default: Optional[Callable[[Any], Any]] = None,
    **kwargs: Any,
) -> bytes:
    """Return JSON string bytes for given data"""
    return bytes(
        jsonlib.dumpb(
            data,
            fmt=fmt,
            pretty=pretty,
            sort_keys=sort_keys,
            append_newline=append_newline,
            default=default,
            **kwargs,
        )
    )

jsonbourne.core.JsonModule.dumps(data: Any, fmt: bool = False, pretty: bool = False, sort_keys: bool = False, append_newline: bool = False, default: Optional[Callable[[Any], Any]] = None, **kwargs: Any) -> str staticmethod ⚓︎

Return JSON stringified/dumps-ed data

Source code in libs/jsonbourne/jsonbourne/core.py
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
@staticmethod
def dumps(
    data: Any,
    fmt: bool = False,
    pretty: bool = False,
    sort_keys: bool = False,
    append_newline: bool = False,
    default: Optional[Callable[[Any], Any]] = None,
    **kwargs: Any,
) -> str:
    """Return JSON stringified/dumps-ed data"""
    return str(
        jsonlib.dumps(
            data,
            fmt=fmt,
            pretty=pretty,
            sort_keys=sort_keys,
            append_newline=append_newline,
            default=default,
            **kwargs,
        )
    )

jsonbourne.core.JsonModule.json_lib() -> str staticmethod ⚓︎

Return the name of the JSON library being used as a backend

Source code in libs/jsonbourne/jsonbourne/core.py
1386
1387
1388
1389
@staticmethod
def json_lib() -> str:
    """Return the name of the JSON library being used as a backend"""
    return jsonlib.which()

jsonbourne.core.JsonModule.jsonify(value: Any) -> Any staticmethod ⚓︎

Alias for jsonbourne.core.jsonify

Source code in libs/jsonbourne/jsonbourne/core.py
1391
1392
1393
1394
@staticmethod
def jsonify(value: Any) -> Any:
    """Alias for jsonbourne.core.jsonify"""
    return jsonify(value)

jsonbourne.core.JsonModule.loads(string: Union[bytes, str], obj: bool = False, jsonc: bool = False, jsonl: bool = False, ndjson: bool = False, **kwargs: Any) -> Any staticmethod ⚓︎

Parse JSON string/bytes and return raw representation

Source code in libs/jsonbourne/jsonbourne/core.py
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
@staticmethod
def loads(
    string: Union[bytes, str],
    obj: bool = False,
    jsonc: bool = False,
    jsonl: bool = False,
    ndjson: bool = False,
    **kwargs: Any,
) -> Any:
    """Parse JSON string/bytes and return raw representation"""
    if obj:
        return jsonify(
            jsonlib.loads(string, jsonc=jsonc, jsonl=jsonl, ndjson=ndjson, **kwargs)
        )
    return jsonlib.loads(string, jsonc=jsonc, jsonl=jsonl, ndjson=ndjson, **kwargs)

jsonbourne.core.JsonModule.parse(string: Union[bytes, str], obj: bool = False, jsonc: bool = False, jsonl: bool = False, ndjson: bool = False, **kwargs: Any) -> Any staticmethod ⚓︎

Parse JSON string/bytes

Source code in libs/jsonbourne/jsonbourne/core.py
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
@staticmethod
def parse(
    string: Union[bytes, str],
    obj: bool = False,
    jsonc: bool = False,
    jsonl: bool = False,
    ndjson: bool = False,
    **kwargs: Any,
) -> Any:
    """Parse JSON string/bytes"""
    if obj:
        return jsonify(
            jsonlib.loads(string, jsonc=jsonc, jsonl=jsonl, ndjson=ndjson, **kwargs)
        )
    return jsonlib.loads(string, jsonc=jsonc, jsonl=jsonl, ndjson=ndjson, **kwargs)

jsonbourne.core.JsonModule.rjson(fspath: Union[Path, str], jsonc: bool = False, jsonl: bool = False, ndjson: bool = False, **kwargs: Any) -> Any staticmethod ⚓︎

Read JSON file and return raw representation

Source code in libs/jsonbourne/jsonbourne/core.py
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
@staticmethod
def rjson(
    fspath: Union[Path, str],
    jsonc: bool = False,
    jsonl: bool = False,
    ndjson: bool = False,
    **kwargs: Any,
) -> Any:
    """Read JSON file and return raw representation"""
    return jsonlib.rjson(fspath, jsonc=jsonc, jsonl=jsonl, ndjson=ndjson, **kwargs)

jsonbourne.core.JsonModule.stringify(data: Any, fmt: bool = False, pretty: bool = False, sort_keys: bool = False, append_newline: bool = False, default: Optional[Callable[[Any], Any]] = None, **kwargs: Any) -> str staticmethod ⚓︎

Return JSON stringified/dumps-ed data

Source code in libs/jsonbourne/jsonbourne/core.py
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
@staticmethod
def stringify(
    data: Any,
    fmt: bool = False,
    pretty: bool = False,
    sort_keys: bool = False,
    append_newline: bool = False,
    default: Optional[Callable[[Any], Any]] = None,
    **kwargs: Any,
) -> str:
    """Return JSON stringified/dumps-ed data"""
    return str(
        jsonlib.dumps(
            data,
            fmt=fmt,
            pretty=pretty,
            sort_keys=sort_keys,
            append_newline=append_newline,
            default=default,
            **kwargs,
        )
    )

jsonbourne.core.JsonModule.unjsonify(value: Any) -> Any staticmethod ⚓︎

Alias for jsonbourne.core.unjsonify

Source code in libs/jsonbourne/jsonbourne/core.py
1396
1397
1398
1399
@staticmethod
def unjsonify(value: Any) -> Any:
    """Alias for jsonbourne.core.unjsonify"""
    return unjsonify(value)

jsonbourne.core.JsonModule.which() -> str staticmethod ⚓︎

Return the name of the JSON library being used as a backend

Source code in libs/jsonbourne/jsonbourne/core.py
1381
1382
1383
1384
@staticmethod
def which() -> str:
    """Return the name of the JSON library being used as a backend"""
    return jsonlib.which()

jsonbourne.core.JsonModule.wjson(fspath: Union[Path, str], data: Any, fmt: bool = False, pretty: bool = False, sort_keys: bool = False, append_newline: bool = False, default: Optional[Callable[[Any], Any]] = None, **kwargs: Any) -> int staticmethod ⚓︎

Write JSON file

Source code in libs/jsonbourne/jsonbourne/core.py
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
@staticmethod
def wjson(
    fspath: Union[Path, str],
    data: Any,
    fmt: bool = False,
    pretty: bool = False,
    sort_keys: bool = False,
    append_newline: bool = False,
    default: Optional[Callable[[Any], Any]] = None,
    **kwargs: Any,
) -> int:
    """Write JSON file"""
    return jsonlib.wjson(
        fspath,
        data,
        fmt=fmt,
        pretty=pretty,
        sort_keys=sort_keys,
        append_newline=append_newline,
        default=default,
        **kwargs,
    )

jsonbourne ⚓︎

jsonbourne the best undercover json lib

Dynamic Graphics Python

Classes⚓︎

jsonbourne.JsonDict(*args: Any, **kwargs: _VT) ⚓︎

Bases: JsonObj[_VT], Generic[_VT]

Alias for JsonObj

Source code in libs/jsonbourne/jsonbourne/core.py
242
243
244
245
246
247
248
249
250
251
252
253
254
def __init__(
    self,
    *args: Any,
    **kwargs: _VT,
) -> None:
    """Use the object dict"""
    _data = dict(*args, **kwargs)
    super().__setattr__("_data", _data)
    if not all(isinstance(k, str) for k in self._data):
        d = {k: v for k, v in self._data.items() if not isinstance(k, str)}  # type: ignore[redundant-expr]
        raise ValueError(f"JsonObj keys MUST be strings! Bad key values: {str(d)}")
    self.recurse()
    self.__post_init__()

jsonbourne.JsonObj(*args: Any, **kwargs: _VT) ⚓︎

Bases: MutableMapping[str, _VT], Generic[_VT]

JSON friendly python dictionary with dot notation and string only keys

JsonObj(foo='bar')['foo'] == JsonObj(foo='bar').foo

Examples:

>>> print(JsonObj())
JsonObj(**{})
>>> d = {"uno": 1, "dos": 2, "tres": 3}
>>> d
{'uno': 1, 'dos': 2, 'tres': 3}
>>> d = JsonObj(d)
>>> d
JsonObj(**{'uno': 1, 'dos': 2, 'tres': 3})
>>> list(d.keys())
['uno', 'dos', 'tres']
>>> list(d.dot_keys())
[('uno',), ('dos',), ('tres',)]
>>> d
JsonObj(**{'uno': 1, 'dos': 2, 'tres': 3})
>>> d['uno']
1
>>> d.uno
1
>>> d['uno'] == d.uno
True
>>> d.uno = "ONE"
>>> d
JsonObj(**{'uno': 'ONE', 'dos': 2, 'tres': 3})
>>> d['uno'] == d.uno
True
>>> 'uno' in d
True
>>> 'not_in_d' in d
False
>>> d
JsonObj(**{'uno': 'ONE', 'dos': 2, 'tres': 3})
>>> del d['dos']
>>> d
JsonObj(**{'uno': 'ONE', 'tres': 3})
>>> d.tres
3
>>> del d.tres
>>> d
JsonObj(**{'uno': 'ONE'})
>>> d = {"uno": 1, "dos": 2, "tres": {"a": 1, "b": [3, 4, 5, 6]}}
>>> d = JsonObj(d)
>>> d
JsonObj(**{'uno': 1, 'dos': 2, 'tres': {'a': 1, 'b': [3, 4, 5, 6]}})
>>> d.tres
JsonObj(**{'a': 1, 'b': [3, 4, 5, 6]})
>>> d.tres.a
1
>>> d.tres.a = "new-val"
>>> d.tres.a
'new-val'
>>> d
JsonObj(**{'uno': 1, 'dos': 2, 'tres': {'a': 'new-val', 'b': [3, 4, 5, 6]}})
>>> jd = JsonObj({"a":1, "b": 'herm', 'alist':[{'sub': 123}]})

It does lists!? oh my

>>> jd
JsonObj(**{'a': 1, 'b': 'herm', 'alist': [{'sub': 123}]})
>>> jd.alist[0]
JsonObj(**{'sub': 123})
>>> jd.eject()
{'a': 1, 'b': 'herm', 'alist': [{'sub': 123}]}
Source code in libs/jsonbourne/jsonbourne/core.py
242
243
244
245
246
247
248
249
250
251
252
253
254
def __init__(
    self,
    *args: Any,
    **kwargs: _VT,
) -> None:
    """Use the object dict"""
    _data = dict(*args, **kwargs)
    super().__setattr__("_data", _data)
    if not all(isinstance(k, str) for k in self._data):
        d = {k: v for k, v in self._data.items() if not isinstance(k, str)}  # type: ignore[redundant-expr]
        raise ValueError(f"JsonObj keys MUST be strings! Bad key values: {str(d)}")
    self.recurse()
    self.__post_init__()
Functions⚓︎
jsonbourne.JsonObj.JSON(fmt: bool = False, pretty: bool = False, sort_keys: bool = False, append_newline: bool = False, default: Optional[Callable[[Any], Any]] = None, **kwargs: Any) -> str ⚓︎

Return JSON string of the JsonObj object (and children)

    Args:
        fmt (bool): If True, return a JSON string with newlines and indentation
        pretty (bool): If True, return a JSON string with newlines and indentation
        sort_keys (bool): Sort dictionary keys if True
        append_newline (bool): Append a newline '

' to JSON string if True default: default function hook for JSON serialization **kwargs (Any): additional kwargs to be passed down to jsonlib.dumps

    Returns:
        str: JSON string of the JsonObj object
Source code in libs/jsonbourne/jsonbourne/core.py
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
def JSON(
    self,
    fmt: bool = False,
    pretty: bool = False,
    sort_keys: bool = False,
    append_newline: bool = False,
    default: Optional[Callable[[Any], Any]] = None,
    **kwargs: Any,
) -> str:
    """Return JSON string of the JsonObj object (and children)

    Args:
        fmt (bool): If True, return a JSON string with newlines and indentation
        pretty (bool): If True, return a JSON string with newlines and indentation
        sort_keys (bool): Sort dictionary keys if True
        append_newline (bool): Append a newline '\n' to JSON string if True
        default: default function hook for JSON serialization
        **kwargs (Any): additional kwargs to be passed down to jsonlib.dumps

    Returns:
        str: JSON string of the JsonObj object

    """
    return jsonlib.dumps(
        self.to_dict(),
        fmt=fmt,
        pretty=pretty,
        sort_keys=sort_keys,
        append_newline=append_newline,
        default=default,
        **kwargs,
    )
jsonbourne.JsonObj.__contains__(key: _KT) -> bool ⚓︎

Check if a key or dot-key is contained within the JsonObj object

Parameters:

Name Type Description Default
key _KT

root level key or a dot-key

required

Returns:

Name Type Description
bool bool

True if the key/dot-key is in the JsonObj; False otherwise

Examples:

>>> d = {"uno": 1, "dos": 2, "tres": 3, "sub": {"a": 1, "b": 2, "c": [3, 4, 5, 6], "d": "a_string"}}
>>> d = JsonObj(d)
>>> d
JsonObj(**{'uno': 1, 'dos': 2, 'tres': 3, 'sub': {'a': 1, 'b': 2, 'c': [3, 4, 5, 6], 'd': 'a_string'}})
>>> 'uno' in d
True
>>> 'this_key_is_not_in_d' in d
False
>>> 'sub.a' in d
True
>>> 'sub.d.a' in d
False
Source code in libs/jsonbourne/jsonbourne/core.py
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
def __contains__(self, key: _KT) -> bool:  # type: ignore[override]
    """Check if a key or dot-key is contained within the JsonObj object

    Args:
        key (_KT): root level key or a dot-key

    Returns:
        bool: True if the key/dot-key is in the JsonObj; False otherwise

    Examples:
        >>> d = {"uno": 1, "dos": 2, "tres": 3, "sub": {"a": 1, "b": 2, "c": [3, 4, 5, 6], "d": "a_string"}}
        >>> d = JsonObj(d)
        >>> d
        JsonObj(**{'uno': 1, 'dos': 2, 'tres': 3, 'sub': {'a': 1, 'b': 2, 'c': [3, 4, 5, 6], 'd': 'a_string'}})
        >>> 'uno' in d
        True
        >>> 'this_key_is_not_in_d' in d
        False
        >>> 'sub.a' in d
        True
        >>> 'sub.d.a' in d
        False

    """
    if "." in key:
        first_key, _, rest = key.partition(".")
        val = self._data.get(first_key)
        return isinstance(val, MutableMapping) and val.__contains__(rest)
    return key in self._data
jsonbourne.JsonObj.__get_type_validator__(source_type: Any, handler: GetCoreSchemaHandler) -> Iterator[Callable[[Any], Any]] classmethod ⚓︎

Return the JsonObj validator functions

Source code in libs/jsonbourne/jsonbourne/core.py
1069
1070
1071
1072
1073
1074
@classmethod
def __get_type_validator__(
    cls, source_type: Any, handler: GetCoreSchemaHandler
) -> Iterator[Callable[[Any], Any]]:
    """Return the JsonObj validator functions"""
    yield cls.validate_type
jsonbourne.JsonObj.__getattr__(item: _KT) -> Any ⚓︎

Return an attr

Examples:

>>> d = {
...     'falsey_dict': {},
...     'falsey_list': [],
...     'falsey_string': '',
...     'is_false': False,
...     'a': None,
...     'b': 2,
...     'c': {
...         'd': 'herm',
...         'e': None,
...         'falsey_dict': {},
...         'falsey_list': [],
...         'falsey_string': '',
...         'is_false': False,
...     },
...     }
...
>>> d = JsonObj(d)
>>> d.__getattr__('b')
2
>>> d.b
2
Source code in libs/jsonbourne/jsonbourne/core.py
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
def __getattr__(self, item: _KT) -> Any:
    """Return an attr

    Examples:
        >>> d = {
        ...     'falsey_dict': {},
        ...     'falsey_list': [],
        ...     'falsey_string': '',
        ...     'is_false': False,
        ...     'a': None,
        ...     'b': 2,
        ...     'c': {
        ...         'd': 'herm',
        ...         'e': None,
        ...         'falsey_dict': {},
        ...         'falsey_list': [],
        ...         'falsey_string': '',
        ...         'is_false': False,
        ...     },
        ...     }
        ...
        >>> d = JsonObj(d)
        >>> d.__getattr__('b')
        2
        >>> d.b
        2

    """
    if item == "_data":
        try:
            return object.__getattribute__(self, "_data")
        except AttributeError:
            return self.__dict__
    if item in _JsonObjMutableMapping_attrs or item in self._cls_protected_attrs():
        return object.__getattribute__(self, item)
    try:
        return jsonify(self.__getitem__(str(item)))
    except KeyError:
        pass
    return object.__getattribute__(self, item)
jsonbourne.JsonObj.__post_init__() -> Any ⚓︎

Function place holder that is called after object initialization

Source code in libs/jsonbourne/jsonbourne/core.py
263
264
def __post_init__(self) -> Any:
    """Function place holder that is called after object initialization"""
jsonbourne.JsonObj.__repr__() -> str ⚓︎

Return the string representation of the object

Source code in libs/jsonbourne/jsonbourne/core.py
789
790
791
def __repr__(self) -> str:
    """Return the string representation of the object"""
    return self.to_str(minify=True)
jsonbourne.JsonObj.__setitem__(key: _KT, value: _VT) -> None ⚓︎

Set JsonObj item with 'key' to 'value'

Parameters:

Name Type Description Default
key _KT

Key/item to set

required
value _VT

Value to set

required

Returns:

Type Description
None

None

Raises:

Type Description
ValueError

If given a key that is not a valid python keyword/identifier

Examples:

>>> d = JsonObj()
>>> d.a = 123
>>> d['b'] = 321
>>> d
JsonObj(**{'a': 123, 'b': 321})
>>> d[123] = 'a'
>>> d
JsonObj(**{'a': 123, 'b': 321, '123': 'a'})
>>> d['456'] = 'a'
>>> d
JsonObj(**{'a': 123, 'b': 321, '123': 'a', '456': 'a'})
Source code in libs/jsonbourne/jsonbourne/core.py
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
def __setitem__(self, key: _KT, value: _VT) -> None:
    """Set JsonObj item with 'key' to 'value'

    Args:
        key (_KT): Key/item to set
        value: Value to set

    Returns:
        None

    Raises:
        ValueError: If given a key that is not a valid python keyword/identifier

    Examples:
        >>> d = JsonObj()
        >>> d.a = 123
        >>> d['b'] = 321
        >>> d
        JsonObj(**{'a': 123, 'b': 321})
        >>> d[123] = 'a'
        >>> d
        JsonObj(**{'a': 123, 'b': 321, '123': 'a'})
        >>> d['456'] = 'a'
        >>> d
        JsonObj(**{'a': 123, 'b': 321, '123': 'a', '456': 'a'})

    """
    self.__setitem(key, value, identifier=False)
jsonbourne.JsonObj.__str__() -> str ⚓︎

Return the string representation of the JsonObj object

Source code in libs/jsonbourne/jsonbourne/core.py
793
794
795
def __str__(self) -> str:
    """Return the string representation of the JsonObj object"""
    return self.to_str(minify=False)
jsonbourne.JsonObj.asdict() -> Dict[_KT, Any] ⚓︎

Return the JsonObj object (and children) as a python dictionary

Source code in libs/jsonbourne/jsonbourne/core.py
894
895
896
def asdict(self) -> Dict[_KT, Any]:
    """Return the JsonObj object (and children) as a python dictionary"""
    return self.eject()
jsonbourne.JsonObj.dot_items() -> Iterator[Tuple[Tuple[str, ...], _VT]] ⚓︎

Yield tuples of the form (dot-key, value)

OG-version

def dot_items(self) -> Iterator[Tuple[str, Any]]: return ((dk, self.dot_lookup(dk)) for dk in self.dot_keys())

Readable-version

for k, value in self.items(): value = jsonify(value) if isinstance(value, JsonObj) or hasattr(value, 'dot_items'): yield from ((f"{k}.{dk}", dv) for dk, dv in value.dot_items()) else: yield k, value

Source code in libs/jsonbourne/jsonbourne/core.py
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
def dot_items(self) -> Iterator[Tuple[Tuple[str, ...], _VT]]:
    """Yield tuples of the form (dot-key, value)

    OG-version:
        def dot_items(self) -> Iterator[Tuple[str, Any]]:
            return ((dk, self.dot_lookup(dk)) for dk in self.dot_keys())

    Readable-version:
        for k, value in self.items():
            value = jsonify(value)
            if isinstance(value, JsonObj) or hasattr(value, 'dot_items'):
                yield from ((f"{k}.{dk}", dv) for dk, dv in value.dot_items())
            else:
                yield k, value
    """

    return chain.from_iterable(
        (
            (
                (
                    *(
                        (
                            (
                                str(k),
                                *dk,
                            ),
                            dv,
                        )
                        for dk, dv in as_json_obj(v).dot_items()
                    ),
                )
                if isinstance(v, (JsonObj, dict))
                else (((str(k),), v),)
            )
            for k, v in self.items()
        )
    )
jsonbourne.JsonObj.dot_items_list() -> List[Tuple[Tuple[str, ...], Any]] ⚓︎

Return list of tuples of the form (dot-key, value)

Source code in libs/jsonbourne/jsonbourne/core.py
763
764
765
def dot_items_list(self) -> List[Tuple[Tuple[str, ...], Any]]:
    """Return list of tuples of the form (dot-key, value)"""
    return list(self.dot_items())
jsonbourne.JsonObj.dot_keys() -> Iterable[Tuple[str, ...]] ⚓︎

Yield the JsonObj's dot-notation keys

Returns:

Type Description
Iterable[Tuple[str, ...]]

Iterable[str]: List of the dot-notation friendly keys

The Non-chain version (shown below) is very slightly slower than the itertools.chain version.

NON-CHAIN VERSION:

for k, value in self.items(): value = jsonify(value) if isinstance(value, JsonObj): yield from (f"{k}.{dk}" for dk in value.dot_keys()) else: yield k

Source code in libs/jsonbourne/jsonbourne/core.py
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
def dot_keys(self) -> Iterable[Tuple[str, ...]]:
    """Yield the JsonObj's dot-notation keys

    Returns:
        Iterable[str]: List of the dot-notation friendly keys


    The Non-chain version (shown below) is very slightly slower than the
    `itertools.chain` version.

    NON-CHAIN VERSION:

    for k, value in self.items():
        value = jsonify(value)
        if isinstance(value, JsonObj):
            yield from (f"{k}.{dk}" for dk in value.dot_keys())
        else:
            yield k

    """
    return chain(
        *(
            (
                ((str(k),),)
                if not isinstance(v, JsonObj)
                else (*((str(k), *dk) for dk in jsonify(v).dot_keys()),)
            )
            for k, v in self.items()
        )
    )
jsonbourne.JsonObj.dot_keys_list(sort_keys: bool = False) -> List[Tuple[str, ...]] ⚓︎

Return a list of the JsonObj's dot-notation friendly keys

Parameters:

Name Type Description Default
sort_keys bool

Flag to have the dot-keys be returned sorted

False

Returns:

Type Description
List[Tuple[str, ...]]

List[str]: List of the dot-notation friendly keys

Source code in libs/jsonbourne/jsonbourne/core.py
660
661
662
663
664
665
666
667
668
669
670
671
672
def dot_keys_list(self, sort_keys: bool = False) -> List[Tuple[str, ...]]:
    """Return a list of the JsonObj's dot-notation friendly keys

    Args:
        sort_keys (bool): Flag to have the dot-keys be returned sorted

    Returns:
        List[str]: List of the dot-notation friendly keys

    """
    if sort_keys:
        return sorted(self.dot_keys_list())
    return list(self.dot_keys())
jsonbourne.JsonObj.dot_keys_set() -> Set[Tuple[str, ...]] ⚓︎

Return a set of the JsonObj's dot-notation friendly keys

Returns:

Type Description
Set[Tuple[str, ...]]

Set[str]: List of the dot-notation friendly keys

Source code in libs/jsonbourne/jsonbourne/core.py
674
675
676
677
678
679
680
681
def dot_keys_set(self) -> Set[Tuple[str, ...]]:
    """Return a set of the JsonObj's dot-notation friendly keys

    Returns:
        Set[str]: List of the dot-notation friendly keys

    """
    return set(self.dot_keys())
jsonbourne.JsonObj.dot_lookup(key: Union[str, Tuple[str, ...], List[str]]) -> Any ⚓︎

Look up JsonObj keys using dot notation as a string

Parameters:

Name Type Description Default
key str

dot-notation key to look up ('key1.key2.third_key')

required

Returns:

Type Description
Any

The result of the dot-notation key look up

Raises:

Type Description
KeyError

Raised if the dot-key is not in in the object

ValueError

Raised if key is not a str/Tuple[str, ...]/List[str]

Source code in libs/jsonbourne/jsonbourne/core.py
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
def dot_lookup(self, key: Union[str, Tuple[str, ...], List[str]]) -> Any:
    """Look up JsonObj keys using dot notation as a string

    Args:
        key (str): dot-notation key to look up ('key1.key2.third_key')

    Returns:
        The result of the dot-notation key look up

    Raises:
        KeyError: Raised if the dot-key is not in in the object
        ValueError: Raised if key is not a str/Tuple[str, ...]/List[str]

    """
    if not isinstance(key, (str, list, tuple)):
        raise ValueError(
            "".join(
                (
                    "dot_key arg must be string or sequence of strings; ",
                    "strings will be split on '.'",
                )
            )
        )
    parts = key.split(".") if isinstance(key, str) else list(key)
    root_val: Any = self._data[parts[0]]
    cur_val = root_val
    for ix, part in enumerate(parts[1:], start=1):
        try:
            cur_val = cur_val[part]
        except TypeError as e:
            reached = ".".join(parts[:ix])
            err_msg = f"Invalid DotKey: {key} -- Lookup reached: {reached} => {str(cur_val)}"
            if isinstance(key, str):
                err_msg += "".join(
                    (
                        f"\nNOTE!!! lookup performed with string ('{key}') ",
                        "PREFER lookup using List[str] or Tuple[str, ...]",
                    )
                )
            raise KeyError(err_msg) from e
    return cur_val
jsonbourne.JsonObj.eject() -> Dict[_KT, _VT] ⚓︎

Eject to python-builtin dictionary object

Examples:

>>> d = JsonObj(**{'uno': 'ONE', 'tres': 3, 'dos': 2})
>>> d
JsonObj(**{'uno': 'ONE', 'tres': 3, 'dos': 2})
>>> plain_ol_dict = d.eject()
>>> plain_ol_dict
{'uno': 'ONE', 'tres': 3, 'dos': 2}
>>> type(plain_ol_dict)
<class 'dict'>
Source code in libs/jsonbourne/jsonbourne/core.py
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
def eject(self) -> Dict[_KT, _VT]:
    """Eject to python-builtin dictionary object

    Examples:
        >>> d = JsonObj(**{'uno': 'ONE', 'tres': 3, 'dos': 2})
        >>> d
        JsonObj(**{'uno': 'ONE', 'tres': 3, 'dos': 2})
        >>> plain_ol_dict = d.eject()
        >>> plain_ol_dict
        {'uno': 'ONE', 'tres': 3, 'dos': 2}
        >>> type(plain_ol_dict)
        <class 'dict'>

    """
    try:
        return {k: unjsonify(v) for k, v in self._data.items()}
    except RecursionError as re:
        raise ValueError(
            "JSON.stringify recursion err; cycle/circular-refs detected"
        ) from re
jsonbourne.JsonObj.entries() -> ItemsView[_KT, _VT] ⚓︎

Alias for items

Source code in libs/jsonbourne/jsonbourne/core.py
434
435
436
def entries(self) -> ItemsView[_KT, _VT]:
    """Alias for items"""
    return self.items()
jsonbourne.JsonObj.filter_false(recursive: bool = False) -> JsonObj[_VT] ⚓︎

Filter key-values where the value is false-y

Parameters:

Name Type Description Default
recursive bool

Recurse into sub JsonObjs and dictionaries

False

Returns:

Type Description
JsonObj[_VT]

JsonObj that has been filtered

Examples:

>>> d = {
...     'falsey_dict': {},
...     'falsey_list': [],
...     'falsey_string': '',
...     'is_false': False,
...     'a': None,
...     'b': 2,
...     'c': {
...         'd': 'herm',
...         'e': None,
...         'falsey_dict': {},
...         'falsey_list': [],
...         'falsey_string': '',
...         'is_false': False,
...     },
...     }
...
>>> d = JsonObj(d)
>>> print(d)
JsonObj(**{
    'a': None,
    'b': 2,
    'c': {'d': 'herm',
          'e': None,
          'falsey_dict': {},
          'falsey_list': [],
          'falsey_string': '',
          'is_false': False},
    'falsey_dict': {},
    'falsey_list': [],
    'falsey_string': '',
    'is_false': False
})
>>> print(d.filter_false())
JsonObj(**{
    'b': 2,
    'c': {'d': 'herm',
          'e': None,
          'falsey_dict': {},
          'falsey_list': [],
          'falsey_string': '',
          'is_false': False}
})
>>> print(d.filter_false(recursive=True))
JsonObj(**{
    'b': 2, 'c': {'d': 'herm'}
})
Source code in libs/jsonbourne/jsonbourne/core.py
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
def filter_false(self, recursive: bool = False) -> JsonObj[_VT]:
    """Filter key-values where the value is false-y

    Args:
        recursive (bool): Recurse into sub JsonObjs and dictionaries

    Returns:
        JsonObj that has been filtered

    Examples:
        >>> d = {
        ...     'falsey_dict': {},
        ...     'falsey_list': [],
        ...     'falsey_string': '',
        ...     'is_false': False,
        ...     'a': None,
        ...     'b': 2,
        ...     'c': {
        ...         'd': 'herm',
        ...         'e': None,
        ...         'falsey_dict': {},
        ...         'falsey_list': [],
        ...         'falsey_string': '',
        ...         'is_false': False,
        ...     },
        ...     }
        ...
        >>> d = JsonObj(d)
        >>> print(d)
        JsonObj(**{
            'a': None,
            'b': 2,
            'c': {'d': 'herm',
                  'e': None,
                  'falsey_dict': {},
                  'falsey_list': [],
                  'falsey_string': '',
                  'is_false': False},
            'falsey_dict': {},
            'falsey_list': [],
            'falsey_string': '',
            'is_false': False
        })
        >>> print(d.filter_false())
        JsonObj(**{
            'b': 2,
            'c': {'d': 'herm',
                  'e': None,
                  'falsey_dict': {},
                  'falsey_list': [],
                  'falsey_string': '',
                  'is_false': False}
        })
        >>> print(d.filter_false(recursive=True))
        JsonObj(**{
            'b': 2, 'c': {'d': 'herm'}
        })

    """
    if recursive:
        return JsonObj(
            cast(
                Dict[str, _VT],
                {
                    k: (
                        v
                        if not isinstance(v, (dict, JsonObj))
                        else JsonObj(v).filter_false(recursive=True)
                    )
                    for k, v in self.items()
                    if v
                },
            )
        )
    return JsonObj({k: v for k, v in self.items() if v})
jsonbourne.JsonObj.filter_none(recursive: bool = False) -> JsonObj[_VT] ⚓︎

Filter key-values where the value is None but not false-y

Parameters:

Name Type Description Default
recursive bool

Recursively filter out None values

False

Returns:

Type Description
JsonObj[_VT]

JsonObj that has been filtered of None values

Examples:

>>> d = {
...     'falsey_dict': {},
...     'falsey_list': [],
...     'falsey_string': '',
...     'is_false': False,
...     'a': None,
...     'b': 2,
...     'c': {
...         'd': 'herm',
...         'e': None,
...         'falsey_dict': {},
...         'falsey_list': [],
...         'falsey_string': '',
...         'is_false': False,
...     },
...     }
...
>>> d = JsonObj(d)
>>> print(d)
JsonObj(**{
    'a': None,
    'b': 2,
    'c': {'d': 'herm',
          'e': None,
          'falsey_dict': {},
          'falsey_list': [],
          'falsey_string': '',
          'is_false': False},
    'falsey_dict': {},
    'falsey_list': [],
    'falsey_string': '',
    'is_false': False
})
>>> print(d.filter_none())
JsonObj(**{
    'b': 2,
    'c': {'d': 'herm',
          'e': None,
          'falsey_dict': {},
          'falsey_list': [],
          'falsey_string': '',
          'is_false': False},
    'falsey_dict': {},
    'falsey_list': [],
    'falsey_string': '',
    'is_false': False
})
>>> from pprint import pprint
>>> print(d.filter_none(recursive=True))
JsonObj(**{
    'b': 2,
    'c': {'d': 'herm',
          'falsey_dict': {},
          'falsey_list': [],
          'falsey_string': '',
          'is_false': False},
    'falsey_dict': {},
    'falsey_list': [],
    'falsey_string': '',
    'is_false': False
})
Source code in libs/jsonbourne/jsonbourne/core.py
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
def filter_none(self, recursive: bool = False) -> JsonObj[_VT]:
    """Filter key-values where the value is `None` but not false-y

    Args:
        recursive (bool): Recursively filter out None values

    Returns:
        JsonObj that has been filtered of None values

    Examples:
        >>> d = {
        ...     'falsey_dict': {},
        ...     'falsey_list': [],
        ...     'falsey_string': '',
        ...     'is_false': False,
        ...     'a': None,
        ...     'b': 2,
        ...     'c': {
        ...         'd': 'herm',
        ...         'e': None,
        ...         'falsey_dict': {},
        ...         'falsey_list': [],
        ...         'falsey_string': '',
        ...         'is_false': False,
        ...     },
        ...     }
        ...
        >>> d = JsonObj(d)
        >>> print(d)
        JsonObj(**{
            'a': None,
            'b': 2,
            'c': {'d': 'herm',
                  'e': None,
                  'falsey_dict': {},
                  'falsey_list': [],
                  'falsey_string': '',
                  'is_false': False},
            'falsey_dict': {},
            'falsey_list': [],
            'falsey_string': '',
            'is_false': False
        })
        >>> print(d.filter_none())
        JsonObj(**{
            'b': 2,
            'c': {'d': 'herm',
                  'e': None,
                  'falsey_dict': {},
                  'falsey_list': [],
                  'falsey_string': '',
                  'is_false': False},
            'falsey_dict': {},
            'falsey_list': [],
            'falsey_string': '',
            'is_false': False
        })
        >>> from pprint import pprint
        >>> print(d.filter_none(recursive=True))
        JsonObj(**{
            'b': 2,
            'c': {'d': 'herm',
                  'falsey_dict': {},
                  'falsey_list': [],
                  'falsey_string': '',
                  'is_false': False},
            'falsey_dict': {},
            'falsey_list': [],
            'falsey_string': '',
            'is_false': False
        })

    """
    if recursive:
        return JsonObj(
            cast(
                Dict[str, _VT],
                {
                    k: (
                        v
                        if not isinstance(v, (dict, JsonObj))
                        else JsonObj(v).filter_none(recursive=True)
                    )
                    for k, v in self.items()
                    if v is not None  # type: ignore[redundant-expr]
                },
            )
        )
    return JsonObj({k: v for k, v in self.items() if v is not None})  # type: ignore[redundant-expr]
jsonbourne.JsonObj.from_dict(data: Dict[_KT, _VT]) -> JsonObj[_VT] classmethod ⚓︎

Return a JsonObj object from a dictionary of data

Source code in libs/jsonbourne/jsonbourne/core.py
898
899
900
901
@classmethod
def from_dict(cls: Type[JsonObj[_VT]], data: Dict[_KT, _VT]) -> JsonObj[_VT]:
    """Return a JsonObj object from a dictionary of data"""
    return cls(**data)
jsonbourne.JsonObj.from_json(json_string: Union[bytes, str]) -> JsonObj[_VT] classmethod ⚓︎

Return a JsonObj object from a json string

Parameters:

Name Type Description Default
json_string str

JSON string to convert to a JsonObj

required

Returns:

Name Type Description
JsonObjT JsonObj[_VT]

JsonObj object for the given JSON string

Source code in libs/jsonbourne/jsonbourne/core.py
903
904
905
906
907
908
909
910
911
912
913
914
915
916
@classmethod
def from_json(
    cls: Type[JsonObj[_VT]], json_string: Union[bytes, str]
) -> JsonObj[_VT]:
    """Return a JsonObj object from a json string

    Args:
        json_string (str): JSON string to convert to a JsonObj

    Returns:
        JsonObjT: JsonObj object for the given JSON string

    """
    return cls._from_json(json_string)
jsonbourne.JsonObj.items() -> ItemsView[_KT, _VT] ⚓︎

Return an items view of the JsonObj object

Source code in libs/jsonbourne/jsonbourne/core.py
430
431
432
def items(self) -> ItemsView[_KT, _VT]:
    """Return an items view of the JsonObj object"""
    return self._data.items()
jsonbourne.JsonObj.keys() -> KeysView[_KT] ⚓︎

Return the keys view of the JsonObj object

Source code in libs/jsonbourne/jsonbourne/core.py
438
439
440
def keys(self) -> KeysView[_KT]:
    """Return the keys view of the JsonObj object"""
    return self._data.keys()
jsonbourne.JsonObj.recurse() -> None ⚓︎

Recursively convert all sub dictionaries to JsonObj objects

Source code in libs/jsonbourne/jsonbourne/core.py
256
257
258
def recurse(self) -> None:
    """Recursively convert all sub dictionaries to JsonObj objects"""
    self._data.update({k: jsonify(v) for k, v in self._data.items()})
jsonbourne.JsonObj.stringify(fmt: bool = False, pretty: bool = False, sort_keys: bool = False, append_newline: bool = False, default: Optional[Callable[[Any], Any]] = None, **kwargs: Any) -> str ⚓︎

Return JSON string of the JsonObj object (and children)

    Args:
        fmt (bool): If True, return a JSON string with newlines and indentation
        pretty (bool): If True, return a JSON string with newlines and indentation
        sort_keys (bool): Sort dictionary keys if True
        append_newline (bool): Append a newline '

' to JSON string if True default: default function hook for JSON serialization **kwargs (Any): additional kwargs to be passed down to jsonlib.dumps

    Returns:
        str: JSON string of the JsonObj object
Source code in libs/jsonbourne/jsonbourne/core.py
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
def stringify(
    self,
    fmt: bool = False,
    pretty: bool = False,
    sort_keys: bool = False,
    append_newline: bool = False,
    default: Optional[Callable[[Any], Any]] = None,
    **kwargs: Any,
) -> str:
    """Return JSON string of the JsonObj object (and children)

    Args:
        fmt (bool): If True, return a JSON string with newlines and indentation
        pretty (bool): If True, return a JSON string with newlines and indentation
        sort_keys (bool): Sort dictionary keys if True
        append_newline (bool): Append a newline '\n' to JSON string if True
        default: default function hook for JSON serialization
        **kwargs (Any): additional kwargs to be passed down to jsonlib.dumps

    Returns:
        str: JSON string of the JsonObj object

    """
    return self._to_json(
        fmt=fmt,
        pretty=pretty,
        sort_keys=sort_keys,
        append_newline=append_newline,
        default=default,
        **kwargs,
    )
jsonbourne.JsonObj.to_dict() -> Dict[_KT, Any] ⚓︎

Return the JsonObj object (and children) as a python dictionary

Source code in libs/jsonbourne/jsonbourne/core.py
890
891
892
def to_dict(self) -> Dict[_KT, Any]:
    """Return the JsonObj object (and children) as a python dictionary"""
    return self.eject()
jsonbourne.JsonObj.to_json(fmt: bool = False, pretty: bool = False, sort_keys: bool = False, append_newline: bool = False, default: Optional[Callable[[Any], Any]] = None, **kwargs: Any) -> str ⚓︎

Return JSON string of the JsonObj object (and children)

    Args:
        fmt (bool): If True, return a JSON string with newlines and indentation
        pretty (bool): If True, return a JSON string with newlines and indentation
        sort_keys (bool): Sort dictionary keys if True
        append_newline (bool): Append a newline '

' to JSON string if True default: default function hook for JSON serialization **kwargs (Any): additional kwargs to be passed down to jsonlib.dumps

    Returns:
        str: JSON string of the JsonObj object
Source code in libs/jsonbourne/jsonbourne/core.py
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
def to_json(
    self,
    fmt: bool = False,
    pretty: bool = False,
    sort_keys: bool = False,
    append_newline: bool = False,
    default: Optional[Callable[[Any], Any]] = None,
    **kwargs: Any,
) -> str:
    """Return JSON string of the JsonObj object (and children)

    Args:
        fmt (bool): If True, return a JSON string with newlines and indentation
        pretty (bool): If True, return a JSON string with newlines and indentation
        sort_keys (bool): Sort dictionary keys if True
        append_newline (bool): Append a newline '\n' to JSON string if True
        default: default function hook for JSON serialization
        **kwargs (Any): additional kwargs to be passed down to jsonlib.dumps

    Returns:
        str: JSON string of the JsonObj object

    """
    return self._to_json(
        fmt=fmt,
        pretty=pretty,
        sort_keys=sort_keys,
        append_newline=append_newline,
        default=default,
        **kwargs,
    )
jsonbourne.JsonObj.to_str(minify: bool = False, width: Optional[int] = None) -> str ⚓︎

Return a string representation of the JsonObj object

Source code in libs/jsonbourne/jsonbourne/core.py
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
def to_str(self, minify: bool = False, width: Optional[int] = None) -> str:
    """Return a string representation of the JsonObj object"""
    if minify:
        return type(self).__name__ + "(**" + str(self.to_dict()) + ")"
    if not bool(self._data):
        return f"{type(self).__name__}(**{{}})"
    _width = get_terminal_size(fallback=(88, 24)).columns - 12
    return "".join(
        [
            type(self).__name__,
            "(**{\n    ",
            pformat(self.eject(), width=_width)[1:-1].replace("\n", "\n   "),
            "\n})",
        ]
    ).replace("JsonObj(**{}),", "{},")
jsonbourne.JsonObj.validate_type(val: Any) -> JsonObj[_VT] classmethod ⚓︎

Validate and convert a value to a JsonObj object

Source code in libs/jsonbourne/jsonbourne/core.py
1064
1065
1066
1067
@classmethod
def validate_type(cls: Type[JsonObj[_VT]], val: Any) -> JsonObj[_VT]:
    """Validate and convert a value to a JsonObj object"""
    return cls(val)

Functions⚓︎

jsonbourne.rm_js_comments(string: str) -> str ⚓︎

Rejects/regex that removes js/ts/json style comments

Source (stackoverflow): https://stackoverflow.com/a/18381470

Source code in libs/jsonbourne/jsonbourne/helpers.py
23
24
25
26
27
28
29
30
31
32
33
def rm_js_comments(string: str) -> str:
    """Rejects/regex that removes js/ts/json style comments

    Source (stackoverflow):
        https://stackoverflow.com/a/18381470
    """
    # first group captures quoted strings (double or single)
    # second group captures comments (//single-line or /* multi-line */)
    regex = re.compile(STRIP_JSON_COMMENTS_REGEX, re.MULTILINE | re.DOTALL)

    return regex.sub(_strip_json_comments_regex_replacer, string)

Modules⚓︎

jsonbourne.__about__ ⚓︎

Package metadata/info

jsonbourne.__main__ ⚓︎

pkg entry ~ python -m jsonbourne

Functions⚓︎
jsonbourne.__main__.main() -> None ⚓︎

Print package metadata

Source code in libs/jsonbourne/jsonbourne/__main__.py
11
12
13
14
15
16
17
18
19
20
21
22
23
24
def main() -> None:
    """Print package metadata"""
    import json

    sys.stdout.write(
        json.dumps(
            {
                "package": __title__,
                "version": __version__,
                "pkgroot": __pkgroot__,
            },
            indent=2,
        )
    )

jsonbourne.core ⚓︎

Json Bourne -- EZ-PZ-JSON with lots o goodies

Classes⚓︎
jsonbourne.core.JSONMeta ⚓︎

Bases: type

Meta type for use by JSON class to allow for static __call__ method

jsonbourne.core.JSONModuleCls() ⚓︎

Bases: ModuleType, JsonModule

Source code in libs/jsonbourne/jsonbourne/core.py
1167
def __init__(self) -> None: ...
Functions⚓︎
jsonbourne.core.JSONModuleCls.__call__(value: Any = None) staticmethod ⚓︎

Jsonify a value

Source code in libs/jsonbourne/jsonbourne/core.py
1408
1409
1410
1411
1412
1413
@staticmethod
def __call__(value: Any = None):  # type: ignore[no-untyped-def]
    """Jsonify a value"""
    if value is None:
        return JsonObj()
    return jsonify(value)
jsonbourne.core.JSONModuleCls.binify(data: Any, fmt: bool = False, pretty: bool = False, sort_keys: bool = False, append_newline: bool = False, default: Optional[Callable[[Any], Any]] = None, **kwargs: Any) -> bytes staticmethod ⚓︎

Return JSON string bytes for given data

Source code in libs/jsonbourne/jsonbourne/core.py
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
@staticmethod
def binify(
    data: Any,
    fmt: bool = False,
    pretty: bool = False,
    sort_keys: bool = False,
    append_newline: bool = False,
    default: Optional[Callable[[Any], Any]] = None,
    **kwargs: Any,
) -> bytes:
    """Return JSON string bytes for given data"""
    return bytes(
        jsonlib.dumpb(
            data,
            fmt=fmt,
            pretty=pretty,
            sort_keys=sort_keys,
            append_newline=append_newline,
            default=default,
            **kwargs,
        )
    )
jsonbourne.core.JSONModuleCls.dumpb(data: Any, fmt: bool = False, pretty: bool = False, sort_keys: bool = False, append_newline: bool = False, default: Optional[Callable[[Any], Any]] = None, **kwargs: Any) -> bytes staticmethod ⚓︎

Return JSON string bytes for given data

Source code in libs/jsonbourne/jsonbourne/core.py
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
@staticmethod
def dumpb(
    data: Any,
    fmt: bool = False,
    pretty: bool = False,
    sort_keys: bool = False,
    append_newline: bool = False,
    default: Optional[Callable[[Any], Any]] = None,
    **kwargs: Any,
) -> bytes:
    """Return JSON string bytes for given data"""
    return bytes(
        jsonlib.dumpb(
            data,
            fmt=fmt,
            pretty=pretty,
            sort_keys=sort_keys,
            append_newline=append_newline,
            default=default,
            **kwargs,
        )
    )
jsonbourne.core.JSONModuleCls.dumps(data: Any, fmt: bool = False, pretty: bool = False, sort_keys: bool = False, append_newline: bool = False, default: Optional[Callable[[Any], Any]] = None, **kwargs: Any) -> str staticmethod ⚓︎

Return JSON stringified/dumps-ed data

Source code in libs/jsonbourne/jsonbourne/core.py
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
@staticmethod
def dumps(
    data: Any,
    fmt: bool = False,
    pretty: bool = False,
    sort_keys: bool = False,
    append_newline: bool = False,
    default: Optional[Callable[[Any], Any]] = None,
    **kwargs: Any,
) -> str:
    """Return JSON stringified/dumps-ed data"""
    return str(
        jsonlib.dumps(
            data,
            fmt=fmt,
            pretty=pretty,
            sort_keys=sort_keys,
            append_newline=append_newline,
            default=default,
            **kwargs,
        )
    )
jsonbourne.core.JSONModuleCls.json_lib() -> str staticmethod ⚓︎

Return the name of the JSON library being used as a backend

Source code in libs/jsonbourne/jsonbourne/core.py
1386
1387
1388
1389
@staticmethod
def json_lib() -> str:
    """Return the name of the JSON library being used as a backend"""
    return jsonlib.which()
jsonbourne.core.JSONModuleCls.jsonify(value: Any) -> Any staticmethod ⚓︎

Alias for jsonbourne.core.jsonify

Source code in libs/jsonbourne/jsonbourne/core.py
1391
1392
1393
1394
@staticmethod
def jsonify(value: Any) -> Any:
    """Alias for jsonbourne.core.jsonify"""
    return jsonify(value)
jsonbourne.core.JSONModuleCls.loads(string: Union[bytes, str], obj: bool = False, jsonc: bool = False, jsonl: bool = False, ndjson: bool = False, **kwargs: Any) -> Any staticmethod ⚓︎

Parse JSON string/bytes and return raw representation

Source code in libs/jsonbourne/jsonbourne/core.py
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
@staticmethod
def loads(
    string: Union[bytes, str],
    obj: bool = False,
    jsonc: bool = False,
    jsonl: bool = False,
    ndjson: bool = False,
    **kwargs: Any,
) -> Any:
    """Parse JSON string/bytes and return raw representation"""
    if obj:
        return jsonify(
            jsonlib.loads(string, jsonc=jsonc, jsonl=jsonl, ndjson=ndjson, **kwargs)
        )
    return jsonlib.loads(string, jsonc=jsonc, jsonl=jsonl, ndjson=ndjson, **kwargs)
jsonbourne.core.JSONModuleCls.parse(string: Union[bytes, str], obj: bool = False, jsonc: bool = False, jsonl: bool = False, ndjson: bool = False, **kwargs: Any) -> Any staticmethod ⚓︎

Parse JSON string/bytes

Source code in libs/jsonbourne/jsonbourne/core.py
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
@staticmethod
def parse(
    string: Union[bytes, str],
    obj: bool = False,
    jsonc: bool = False,
    jsonl: bool = False,
    ndjson: bool = False,
    **kwargs: Any,
) -> Any:
    """Parse JSON string/bytes"""
    if obj:
        return jsonify(
            jsonlib.loads(string, jsonc=jsonc, jsonl=jsonl, ndjson=ndjson, **kwargs)
        )
    return jsonlib.loads(string, jsonc=jsonc, jsonl=jsonl, ndjson=ndjson, **kwargs)
jsonbourne.core.JSONModuleCls.rjson(fspath: Union[Path, str], jsonc: bool = False, jsonl: bool = False, ndjson: bool = False, **kwargs: Any) -> Any staticmethod ⚓︎

Read JSON file and return raw representation

Source code in libs/jsonbourne/jsonbourne/core.py
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
@staticmethod
def rjson(
    fspath: Union[Path, str],
    jsonc: bool = False,
    jsonl: bool = False,
    ndjson: bool = False,
    **kwargs: Any,
) -> Any:
    """Read JSON file and return raw representation"""
    return jsonlib.rjson(fspath, jsonc=jsonc, jsonl=jsonl, ndjson=ndjson, **kwargs)
jsonbourne.core.JSONModuleCls.stringify(data: Any, fmt: bool = False, pretty: bool = False, sort_keys: bool = False, append_newline: bool = False, default: Optional[Callable[[Any], Any]] = None, **kwargs: Any) -> str staticmethod ⚓︎

Return JSON stringified/dumps-ed data

Source code in libs/jsonbourne/jsonbourne/core.py
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
@staticmethod
def stringify(
    data: Any,
    fmt: bool = False,
    pretty: bool = False,
    sort_keys: bool = False,
    append_newline: bool = False,
    default: Optional[Callable[[Any], Any]] = None,
    **kwargs: Any,
) -> str:
    """Return JSON stringified/dumps-ed data"""
    return str(
        jsonlib.dumps(
            data,
            fmt=fmt,
            pretty=pretty,
            sort_keys=sort_keys,
            append_newline=append_newline,
            default=default,
            **kwargs,
        )
    )
jsonbourne.core.JSONModuleCls.unjsonify(value: Any) -> Any staticmethod ⚓︎

Alias for jsonbourne.core.unjsonify

Source code in libs/jsonbourne/jsonbourne/core.py
1396
1397
1398
1399
@staticmethod
def unjsonify(value: Any) -> Any:
    """Alias for jsonbourne.core.unjsonify"""
    return unjsonify(value)
jsonbourne.core.JSONModuleCls.which() -> str staticmethod ⚓︎

Return the name of the JSON library being used as a backend

Source code in libs/jsonbourne/jsonbourne/core.py
1381
1382
1383
1384
@staticmethod
def which() -> str:
    """Return the name of the JSON library being used as a backend"""
    return jsonlib.which()
jsonbourne.core.JSONModuleCls.wjson(fspath: Union[Path, str], data: Any, fmt: bool = False, pretty: bool = False, sort_keys: bool = False, append_newline: bool = False, default: Optional[Callable[[Any], Any]] = None, **kwargs: Any) -> int staticmethod ⚓︎

Write JSON file

Source code in libs/jsonbourne/jsonbourne/core.py
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
@staticmethod
def wjson(
    fspath: Union[Path, str],
    data: Any,
    fmt: bool = False,
    pretty: bool = False,
    sort_keys: bool = False,
    append_newline: bool = False,
    default: Optional[Callable[[Any], Any]] = None,
    **kwargs: Any,
) -> int:
    """Write JSON file"""
    return jsonlib.wjson(
        fspath,
        data,
        fmt=fmt,
        pretty=pretty,
        sort_keys=sort_keys,
        append_newline=append_newline,
        default=default,
        **kwargs,
    )
jsonbourne.core.JsonDict(*args: Any, **kwargs: _VT) ⚓︎

Bases: JsonObj[_VT], Generic[_VT]

Alias for JsonObj

Source code in libs/jsonbourne/jsonbourne/core.py
242
243
244
245
246
247
248
249
250
251
252
253
254
def __init__(
    self,
    *args: Any,
    **kwargs: _VT,
) -> None:
    """Use the object dict"""
    _data = dict(*args, **kwargs)
    super().__setattr__("_data", _data)
    if not all(isinstance(k, str) for k in self._data):
        d = {k: v for k, v in self._data.items() if not isinstance(k, str)}  # type: ignore[redundant-expr]
        raise ValueError(f"JsonObj keys MUST be strings! Bad key values: {str(d)}")
    self.recurse()
    self.__post_init__()
jsonbourne.core.JsonModule() ⚓︎

JSON class meant to mimic the js/ts-JSON

Source code in libs/jsonbourne/jsonbourne/core.py
1167
def __init__(self) -> None: ...
Functions⚓︎
jsonbourne.core.JsonModule.binify(data: Any, fmt: bool = False, pretty: bool = False, sort_keys: bool = False, append_newline: bool = False, default: Optional[Callable[[Any], Any]] = None, **kwargs: Any) -> bytes staticmethod ⚓︎

Return JSON string bytes for given data

Source code in libs/jsonbourne/jsonbourne/core.py
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
@staticmethod
def binify(
    data: Any,
    fmt: bool = False,
    pretty: bool = False,
    sort_keys: bool = False,
    append_newline: bool = False,
    default: Optional[Callable[[Any], Any]] = None,
    **kwargs: Any,
) -> bytes:
    """Return JSON string bytes for given data"""
    return bytes(
        jsonlib.dumpb(
            data,
            fmt=fmt,
            pretty=pretty,
            sort_keys=sort_keys,
            append_newline=append_newline,
            default=default,
            **kwargs,
        )
    )
jsonbourne.core.JsonModule.dumpb(data: Any, fmt: bool = False, pretty: bool = False, sort_keys: bool = False, append_newline: bool = False, default: Optional[Callable[[Any], Any]] = None, **kwargs: Any) -> bytes staticmethod ⚓︎

Return JSON string bytes for given data

Source code in libs/jsonbourne/jsonbourne/core.py
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
@staticmethod
def dumpb(
    data: Any,
    fmt: bool = False,
    pretty: bool = False,
    sort_keys: bool = False,
    append_newline: bool = False,
    default: Optional[Callable[[Any], Any]] = None,
    **kwargs: Any,
) -> bytes:
    """Return JSON string bytes for given data"""
    return bytes(
        jsonlib.dumpb(
            data,
            fmt=fmt,
            pretty=pretty,
            sort_keys=sort_keys,
            append_newline=append_newline,
            default=default,
            **kwargs,
        )
    )
jsonbourne.core.JsonModule.dumps(data: Any, fmt: bool = False, pretty: bool = False, sort_keys: bool = False, append_newline: bool = False, default: Optional[Callable[[Any], Any]] = None, **kwargs: Any) -> str staticmethod ⚓︎

Return JSON stringified/dumps-ed data

Source code in libs/jsonbourne/jsonbourne/core.py
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
@staticmethod
def dumps(
    data: Any,
    fmt: bool = False,
    pretty: bool = False,
    sort_keys: bool = False,
    append_newline: bool = False,
    default: Optional[Callable[[Any], Any]] = None,
    **kwargs: Any,
) -> str:
    """Return JSON stringified/dumps-ed data"""
    return str(
        jsonlib.dumps(
            data,
            fmt=fmt,
            pretty=pretty,
            sort_keys=sort_keys,
            append_newline=append_newline,
            default=default,
            **kwargs,
        )
    )
jsonbourne.core.JsonModule.json_lib() -> str staticmethod ⚓︎

Return the name of the JSON library being used as a backend

Source code in libs/jsonbourne/jsonbourne/core.py
1386
1387
1388
1389
@staticmethod
def json_lib() -> str:
    """Return the name of the JSON library being used as a backend"""
    return jsonlib.which()
jsonbourne.core.JsonModule.jsonify(value: Any) -> Any staticmethod ⚓︎

Alias for jsonbourne.core.jsonify

Source code in libs/jsonbourne/jsonbourne/core.py
1391
1392
1393
1394
@staticmethod
def jsonify(value: Any) -> Any:
    """Alias for jsonbourne.core.jsonify"""
    return jsonify(value)
jsonbourne.core.JsonModule.loads(string: Union[bytes, str], obj: bool = False, jsonc: bool = False, jsonl: bool = False, ndjson: bool = False, **kwargs: Any) -> Any staticmethod ⚓︎

Parse JSON string/bytes and return raw representation

Source code in libs/jsonbourne/jsonbourne/core.py
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
@staticmethod
def loads(
    string: Union[bytes, str],
    obj: bool = False,
    jsonc: bool = False,
    jsonl: bool = False,
    ndjson: bool = False,
    **kwargs: Any,
) -> Any:
    """Parse JSON string/bytes and return raw representation"""
    if obj:
        return jsonify(
            jsonlib.loads(string, jsonc=jsonc, jsonl=jsonl, ndjson=ndjson, **kwargs)
        )
    return jsonlib.loads(string, jsonc=jsonc, jsonl=jsonl, ndjson=ndjson, **kwargs)
jsonbourne.core.JsonModule.parse(string: Union[bytes, str], obj: bool = False, jsonc: bool = False, jsonl: bool = False, ndjson: bool = False, **kwargs: Any) -> Any staticmethod ⚓︎

Parse JSON string/bytes

Source code in libs/jsonbourne/jsonbourne/core.py
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
@staticmethod
def parse(
    string: Union[bytes, str],
    obj: bool = False,
    jsonc: bool = False,
    jsonl: bool = False,
    ndjson: bool = False,
    **kwargs: Any,
) -> Any:
    """Parse JSON string/bytes"""
    if obj:
        return jsonify(
            jsonlib.loads(string, jsonc=jsonc, jsonl=jsonl, ndjson=ndjson, **kwargs)
        )
    return jsonlib.loads(string, jsonc=jsonc, jsonl=jsonl, ndjson=ndjson, **kwargs)
jsonbourne.core.JsonModule.rjson(fspath: Union[Path, str], jsonc: bool = False, jsonl: bool = False, ndjson: bool = False, **kwargs: Any) -> Any staticmethod ⚓︎

Read JSON file and return raw representation

Source code in libs/jsonbourne/jsonbourne/core.py
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
@staticmethod
def rjson(
    fspath: Union[Path, str],
    jsonc: bool = False,
    jsonl: bool = False,
    ndjson: bool = False,
    **kwargs: Any,
) -> Any:
    """Read JSON file and return raw representation"""
    return jsonlib.rjson(fspath, jsonc=jsonc, jsonl=jsonl, ndjson=ndjson, **kwargs)
jsonbourne.core.JsonModule.stringify(data: Any, fmt: bool = False, pretty: bool = False, sort_keys: bool = False, append_newline: bool = False, default: Optional[Callable[[Any], Any]] = None, **kwargs: Any) -> str staticmethod ⚓︎

Return JSON stringified/dumps-ed data

Source code in libs/jsonbourne/jsonbourne/core.py
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
@staticmethod
def stringify(
    data: Any,
    fmt: bool = False,
    pretty: bool = False,
    sort_keys: bool = False,
    append_newline: bool = False,
    default: Optional[Callable[[Any], Any]] = None,
    **kwargs: Any,
) -> str:
    """Return JSON stringified/dumps-ed data"""
    return str(
        jsonlib.dumps(
            data,
            fmt=fmt,
            pretty=pretty,
            sort_keys=sort_keys,
            append_newline=append_newline,
            default=default,
            **kwargs,
        )
    )
jsonbourne.core.JsonModule.unjsonify(value: Any) -> Any staticmethod ⚓︎

Alias for jsonbourne.core.unjsonify

Source code in libs/jsonbourne/jsonbourne/core.py
1396
1397
1398
1399
@staticmethod
def unjsonify(value: Any) -> Any:
    """Alias for jsonbourne.core.unjsonify"""
    return unjsonify(value)
jsonbourne.core.JsonModule.which() -> str staticmethod ⚓︎

Return the name of the JSON library being used as a backend

Source code in libs/jsonbourne/jsonbourne/core.py
1381
1382
1383
1384
@staticmethod
def which() -> str:
    """Return the name of the JSON library being used as a backend"""
    return jsonlib.which()
jsonbourne.core.JsonModule.wjson(fspath: Union[Path, str], data: Any, fmt: bool = False, pretty: bool = False, sort_keys: bool = False, append_newline: bool = False, default: Optional[Callable[[Any], Any]] = None, **kwargs: Any) -> int staticmethod ⚓︎

Write JSON file

Source code in libs/jsonbourne/jsonbourne/core.py
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
@staticmethod
def wjson(
    fspath: Union[Path, str],
    data: Any,
    fmt: bool = False,
    pretty: bool = False,
    sort_keys: bool = False,
    append_newline: bool = False,
    default: Optional[Callable[[Any], Any]] = None,
    **kwargs: Any,
) -> int:
    """Write JSON file"""
    return jsonlib.wjson(
        fspath,
        data,
        fmt=fmt,
        pretty=pretty,
        sort_keys=sort_keys,
        append_newline=append_newline,
        default=default,
        **kwargs,
    )
jsonbourne.core.JsonObj(*args: Any, **kwargs: _VT) ⚓︎

Bases: MutableMapping[str, _VT], Generic[_VT]

JSON friendly python dictionary with dot notation and string only keys

JsonObj(foo='bar')['foo'] == JsonObj(foo='bar').foo

Examples:

>>> print(JsonObj())
JsonObj(**{})
>>> d = {"uno": 1, "dos": 2, "tres": 3}
>>> d
{'uno': 1, 'dos': 2, 'tres': 3}
>>> d = JsonObj(d)
>>> d
JsonObj(**{'uno': 1, 'dos': 2, 'tres': 3})
>>> list(d.keys())
['uno', 'dos', 'tres']
>>> list(d.dot_keys())
[('uno',), ('dos',), ('tres',)]
>>> d
JsonObj(**{'uno': 1, 'dos': 2, 'tres': 3})
>>> d['uno']
1
>>> d.uno
1
>>> d['uno'] == d.uno
True
>>> d.uno = "ONE"
>>> d
JsonObj(**{'uno': 'ONE', 'dos': 2, 'tres': 3})
>>> d['uno'] == d.uno
True
>>> 'uno' in d
True
>>> 'not_in_d' in d
False
>>> d
JsonObj(**{'uno': 'ONE', 'dos': 2, 'tres': 3})
>>> del d['dos']
>>> d
JsonObj(**{'uno': 'ONE', 'tres': 3})
>>> d.tres
3
>>> del d.tres
>>> d
JsonObj(**{'uno': 'ONE'})
>>> d = {"uno": 1, "dos": 2, "tres": {"a": 1, "b": [3, 4, 5, 6]}}
>>> d = JsonObj(d)
>>> d
JsonObj(**{'uno': 1, 'dos': 2, 'tres': {'a': 1, 'b': [3, 4, 5, 6]}})
>>> d.tres
JsonObj(**{'a': 1, 'b': [3, 4, 5, 6]})
>>> d.tres.a
1
>>> d.tres.a = "new-val"
>>> d.tres.a
'new-val'
>>> d
JsonObj(**{'uno': 1, 'dos': 2, 'tres': {'a': 'new-val', 'b': [3, 4, 5, 6]}})
>>> jd = JsonObj({"a":1, "b": 'herm', 'alist':[{'sub': 123}]})

It does lists!? oh my

>>> jd
JsonObj(**{'a': 1, 'b': 'herm', 'alist': [{'sub': 123}]})
>>> jd.alist[0]
JsonObj(**{'sub': 123})
>>> jd.eject()
{'a': 1, 'b': 'herm', 'alist': [{'sub': 123}]}
Source code in libs/jsonbourne/jsonbourne/core.py
242
243
244
245
246
247
248
249
250
251
252
253
254
def __init__(
    self,
    *args: Any,
    **kwargs: _VT,
) -> None:
    """Use the object dict"""
    _data = dict(*args, **kwargs)
    super().__setattr__("_data", _data)
    if not all(isinstance(k, str) for k in self._data):
        d = {k: v for k, v in self._data.items() if not isinstance(k, str)}  # type: ignore[redundant-expr]
        raise ValueError(f"JsonObj keys MUST be strings! Bad key values: {str(d)}")
    self.recurse()
    self.__post_init__()
Functions⚓︎
jsonbourne.core.JsonObj.JSON(fmt: bool = False, pretty: bool = False, sort_keys: bool = False, append_newline: bool = False, default: Optional[Callable[[Any], Any]] = None, **kwargs: Any) -> str ⚓︎

Return JSON string of the JsonObj object (and children)

    Args:
        fmt (bool): If True, return a JSON string with newlines and indentation
        pretty (bool): If True, return a JSON string with newlines and indentation
        sort_keys (bool): Sort dictionary keys if True
        append_newline (bool): Append a newline '

' to JSON string if True default: default function hook for JSON serialization **kwargs (Any): additional kwargs to be passed down to jsonlib.dumps

    Returns:
        str: JSON string of the JsonObj object
Source code in libs/jsonbourne/jsonbourne/core.py
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
def JSON(
    self,
    fmt: bool = False,
    pretty: bool = False,
    sort_keys: bool = False,
    append_newline: bool = False,
    default: Optional[Callable[[Any], Any]] = None,
    **kwargs: Any,
) -> str:
    """Return JSON string of the JsonObj object (and children)

    Args:
        fmt (bool): If True, return a JSON string with newlines and indentation
        pretty (bool): If True, return a JSON string with newlines and indentation
        sort_keys (bool): Sort dictionary keys if True
        append_newline (bool): Append a newline '\n' to JSON string if True
        default: default function hook for JSON serialization
        **kwargs (Any): additional kwargs to be passed down to jsonlib.dumps

    Returns:
        str: JSON string of the JsonObj object

    """
    return jsonlib.dumps(
        self.to_dict(),
        fmt=fmt,
        pretty=pretty,
        sort_keys=sort_keys,
        append_newline=append_newline,
        default=default,
        **kwargs,
    )
jsonbourne.core.JsonObj.__contains__(key: _KT) -> bool ⚓︎

Check if a key or dot-key is contained within the JsonObj object

Parameters:

Name Type Description Default
key _KT

root level key or a dot-key

required

Returns:

Name Type Description
bool bool

True if the key/dot-key is in the JsonObj; False otherwise

Examples:

>>> d = {"uno": 1, "dos": 2, "tres": 3, "sub": {"a": 1, "b": 2, "c": [3, 4, 5, 6], "d": "a_string"}}
>>> d = JsonObj(d)
>>> d
JsonObj(**{'uno': 1, 'dos': 2, 'tres': 3, 'sub': {'a': 1, 'b': 2, 'c': [3, 4, 5, 6], 'd': 'a_string'}})
>>> 'uno' in d
True
>>> 'this_key_is_not_in_d' in d
False
>>> 'sub.a' in d
True
>>> 'sub.d.a' in d
False
Source code in libs/jsonbourne/jsonbourne/core.py
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
def __contains__(self, key: _KT) -> bool:  # type: ignore[override]
    """Check if a key or dot-key is contained within the JsonObj object

    Args:
        key (_KT): root level key or a dot-key

    Returns:
        bool: True if the key/dot-key is in the JsonObj; False otherwise

    Examples:
        >>> d = {"uno": 1, "dos": 2, "tres": 3, "sub": {"a": 1, "b": 2, "c": [3, 4, 5, 6], "d": "a_string"}}
        >>> d = JsonObj(d)
        >>> d
        JsonObj(**{'uno': 1, 'dos': 2, 'tres': 3, 'sub': {'a': 1, 'b': 2, 'c': [3, 4, 5, 6], 'd': 'a_string'}})
        >>> 'uno' in d
        True
        >>> 'this_key_is_not_in_d' in d
        False
        >>> 'sub.a' in d
        True
        >>> 'sub.d.a' in d
        False

    """
    if "." in key:
        first_key, _, rest = key.partition(".")
        val = self._data.get(first_key)
        return isinstance(val, MutableMapping) and val.__contains__(rest)
    return key in self._data
jsonbourne.core.JsonObj.__get_type_validator__(source_type: Any, handler: GetCoreSchemaHandler) -> Iterator[Callable[[Any], Any]] classmethod ⚓︎

Return the JsonObj validator functions

Source code in libs/jsonbourne/jsonbourne/core.py
1069
1070
1071
1072
1073
1074
@classmethod
def __get_type_validator__(
    cls, source_type: Any, handler: GetCoreSchemaHandler
) -> Iterator[Callable[[Any], Any]]:
    """Return the JsonObj validator functions"""
    yield cls.validate_type
jsonbourne.core.JsonObj.__getattr__(item: _KT) -> Any ⚓︎

Return an attr

Examples:

>>> d = {
...     'falsey_dict': {},
...     'falsey_list': [],
...     'falsey_string': '',
...     'is_false': False,
...     'a': None,
...     'b': 2,
...     'c': {
...         'd': 'herm',
...         'e': None,
...         'falsey_dict': {},
...         'falsey_list': [],
...         'falsey_string': '',
...         'is_false': False,
...     },
...     }
...
>>> d = JsonObj(d)
>>> d.__getattr__('b')
2
>>> d.b
2
Source code in libs/jsonbourne/jsonbourne/core.py
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
def __getattr__(self, item: _KT) -> Any:
    """Return an attr

    Examples:
        >>> d = {
        ...     'falsey_dict': {},
        ...     'falsey_list': [],
        ...     'falsey_string': '',
        ...     'is_false': False,
        ...     'a': None,
        ...     'b': 2,
        ...     'c': {
        ...         'd': 'herm',
        ...         'e': None,
        ...         'falsey_dict': {},
        ...         'falsey_list': [],
        ...         'falsey_string': '',
        ...         'is_false': False,
        ...     },
        ...     }
        ...
        >>> d = JsonObj(d)
        >>> d.__getattr__('b')
        2
        >>> d.b
        2

    """
    if item == "_data":
        try:
            return object.__getattribute__(self, "_data")
        except AttributeError:
            return self.__dict__
    if item in _JsonObjMutableMapping_attrs or item in self._cls_protected_attrs():
        return object.__getattribute__(self, item)
    try:
        return jsonify(self.__getitem__(str(item)))
    except KeyError:
        pass
    return object.__getattribute__(self, item)
jsonbourne.core.JsonObj.__post_init__() -> Any ⚓︎

Function place holder that is called after object initialization

Source code in libs/jsonbourne/jsonbourne/core.py
263
264
def __post_init__(self) -> Any:
    """Function place holder that is called after object initialization"""
jsonbourne.core.JsonObj.__repr__() -> str ⚓︎

Return the string representation of the object

Source code in libs/jsonbourne/jsonbourne/core.py
789
790
791
def __repr__(self) -> str:
    """Return the string representation of the object"""
    return self.to_str(minify=True)
jsonbourne.core.JsonObj.__setitem__(key: _KT, value: _VT) -> None ⚓︎

Set JsonObj item with 'key' to 'value'

Parameters:

Name Type Description Default
key _KT

Key/item to set

required
value _VT

Value to set

required

Returns:

Type Description
None

None

Raises:

Type Description
ValueError

If given a key that is not a valid python keyword/identifier

Examples:

>>> d = JsonObj()
>>> d.a = 123
>>> d['b'] = 321
>>> d
JsonObj(**{'a': 123, 'b': 321})
>>> d[123] = 'a'
>>> d
JsonObj(**{'a': 123, 'b': 321, '123': 'a'})
>>> d['456'] = 'a'
>>> d
JsonObj(**{'a': 123, 'b': 321, '123': 'a', '456': 'a'})
Source code in libs/jsonbourne/jsonbourne/core.py
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
def __setitem__(self, key: _KT, value: _VT) -> None:
    """Set JsonObj item with 'key' to 'value'

    Args:
        key (_KT): Key/item to set
        value: Value to set

    Returns:
        None

    Raises:
        ValueError: If given a key that is not a valid python keyword/identifier

    Examples:
        >>> d = JsonObj()
        >>> d.a = 123
        >>> d['b'] = 321
        >>> d
        JsonObj(**{'a': 123, 'b': 321})
        >>> d[123] = 'a'
        >>> d
        JsonObj(**{'a': 123, 'b': 321, '123': 'a'})
        >>> d['456'] = 'a'
        >>> d
        JsonObj(**{'a': 123, 'b': 321, '123': 'a', '456': 'a'})

    """
    self.__setitem(key, value, identifier=False)
jsonbourne.core.JsonObj.__str__() -> str ⚓︎

Return the string representation of the JsonObj object

Source code in libs/jsonbourne/jsonbourne/core.py
793
794
795
def __str__(self) -> str:
    """Return the string representation of the JsonObj object"""
    return self.to_str(minify=False)
jsonbourne.core.JsonObj.asdict() -> Dict[_KT, Any] ⚓︎

Return the JsonObj object (and children) as a python dictionary

Source code in libs/jsonbourne/jsonbourne/core.py
894
895
896
def asdict(self) -> Dict[_KT, Any]:
    """Return the JsonObj object (and children) as a python dictionary"""
    return self.eject()
jsonbourne.core.JsonObj.dot_items() -> Iterator[Tuple[Tuple[str, ...], _VT]] ⚓︎

Yield tuples of the form (dot-key, value)

OG-version

def dot_items(self) -> Iterator[Tuple[str, Any]]: return ((dk, self.dot_lookup(dk)) for dk in self.dot_keys())

Readable-version

for k, value in self.items(): value = jsonify(value) if isinstance(value, JsonObj) or hasattr(value, 'dot_items'): yield from ((f"{k}.{dk}", dv) for dk, dv in value.dot_items()) else: yield k, value

Source code in libs/jsonbourne/jsonbourne/core.py
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
def dot_items(self) -> Iterator[Tuple[Tuple[str, ...], _VT]]:
    """Yield tuples of the form (dot-key, value)

    OG-version:
        def dot_items(self) -> Iterator[Tuple[str, Any]]:
            return ((dk, self.dot_lookup(dk)) for dk in self.dot_keys())

    Readable-version:
        for k, value in self.items():
            value = jsonify(value)
            if isinstance(value, JsonObj) or hasattr(value, 'dot_items'):
                yield from ((f"{k}.{dk}", dv) for dk, dv in value.dot_items())
            else:
                yield k, value
    """

    return chain.from_iterable(
        (
            (
                (
                    *(
                        (
                            (
                                str(k),
                                *dk,
                            ),
                            dv,
                        )
                        for dk, dv in as_json_obj(v).dot_items()
                    ),
                )
                if isinstance(v, (JsonObj, dict))
                else (((str(k),), v),)
            )
            for k, v in self.items()
        )
    )
jsonbourne.core.JsonObj.dot_items_list() -> List[Tuple[Tuple[str, ...], Any]] ⚓︎

Return list of tuples of the form (dot-key, value)

Source code in libs/jsonbourne/jsonbourne/core.py
763
764
765
def dot_items_list(self) -> List[Tuple[Tuple[str, ...], Any]]:
    """Return list of tuples of the form (dot-key, value)"""
    return list(self.dot_items())
jsonbourne.core.JsonObj.dot_keys() -> Iterable[Tuple[str, ...]] ⚓︎

Yield the JsonObj's dot-notation keys

Returns:

Type Description
Iterable[Tuple[str, ...]]

Iterable[str]: List of the dot-notation friendly keys

The Non-chain version (shown below) is very slightly slower than the itertools.chain version.

NON-CHAIN VERSION:

for k, value in self.items(): value = jsonify(value) if isinstance(value, JsonObj): yield from (f"{k}.{dk}" for dk in value.dot_keys()) else: yield k

Source code in libs/jsonbourne/jsonbourne/core.py
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
def dot_keys(self) -> Iterable[Tuple[str, ...]]:
    """Yield the JsonObj's dot-notation keys

    Returns:
        Iterable[str]: List of the dot-notation friendly keys


    The Non-chain version (shown below) is very slightly slower than the
    `itertools.chain` version.

    NON-CHAIN VERSION:

    for k, value in self.items():
        value = jsonify(value)
        if isinstance(value, JsonObj):
            yield from (f"{k}.{dk}" for dk in value.dot_keys())
        else:
            yield k

    """
    return chain(
        *(
            (
                ((str(k),),)
                if not isinstance(v, JsonObj)
                else (*((str(k), *dk) for dk in jsonify(v).dot_keys()),)
            )
            for k, v in self.items()
        )
    )
jsonbourne.core.JsonObj.dot_keys_list(sort_keys: bool = False) -> List[Tuple[str, ...]] ⚓︎

Return a list of the JsonObj's dot-notation friendly keys

Parameters:

Name Type Description Default
sort_keys bool

Flag to have the dot-keys be returned sorted

False

Returns:

Type Description
List[Tuple[str, ...]]

List[str]: List of the dot-notation friendly keys

Source code in libs/jsonbourne/jsonbourne/core.py
660
661
662
663
664
665
666
667
668
669
670
671
672
def dot_keys_list(self, sort_keys: bool = False) -> List[Tuple[str, ...]]:
    """Return a list of the JsonObj's dot-notation friendly keys

    Args:
        sort_keys (bool): Flag to have the dot-keys be returned sorted

    Returns:
        List[str]: List of the dot-notation friendly keys

    """
    if sort_keys:
        return sorted(self.dot_keys_list())
    return list(self.dot_keys())
jsonbourne.core.JsonObj.dot_keys_set() -> Set[Tuple[str, ...]] ⚓︎

Return a set of the JsonObj's dot-notation friendly keys

Returns:

Type Description
Set[Tuple[str, ...]]

Set[str]: List of the dot-notation friendly keys

Source code in libs/jsonbourne/jsonbourne/core.py
674
675
676
677
678
679
680
681
def dot_keys_set(self) -> Set[Tuple[str, ...]]:
    """Return a set of the JsonObj's dot-notation friendly keys

    Returns:
        Set[str]: List of the dot-notation friendly keys

    """
    return set(self.dot_keys())
jsonbourne.core.JsonObj.dot_lookup(key: Union[str, Tuple[str, ...], List[str]]) -> Any ⚓︎

Look up JsonObj keys using dot notation as a string

Parameters:

Name Type Description Default
key str

dot-notation key to look up ('key1.key2.third_key')

required

Returns:

Type Description
Any

The result of the dot-notation key look up

Raises:

Type Description
KeyError

Raised if the dot-key is not in in the object

ValueError

Raised if key is not a str/Tuple[str, ...]/List[str]

Source code in libs/jsonbourne/jsonbourne/core.py
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
def dot_lookup(self, key: Union[str, Tuple[str, ...], List[str]]) -> Any:
    """Look up JsonObj keys using dot notation as a string

    Args:
        key (str): dot-notation key to look up ('key1.key2.third_key')

    Returns:
        The result of the dot-notation key look up

    Raises:
        KeyError: Raised if the dot-key is not in in the object
        ValueError: Raised if key is not a str/Tuple[str, ...]/List[str]

    """
    if not isinstance(key, (str, list, tuple)):
        raise ValueError(
            "".join(
                (
                    "dot_key arg must be string or sequence of strings; ",
                    "strings will be split on '.'",
                )
            )
        )
    parts = key.split(".") if isinstance(key, str) else list(key)
    root_val: Any = self._data[parts[0]]
    cur_val = root_val
    for ix, part in enumerate(parts[1:], start=1):
        try:
            cur_val = cur_val[part]
        except TypeError as e:
            reached = ".".join(parts[:ix])
            err_msg = f"Invalid DotKey: {key} -- Lookup reached: {reached} => {str(cur_val)}"
            if isinstance(key, str):
                err_msg += "".join(
                    (
                        f"\nNOTE!!! lookup performed with string ('{key}') ",
                        "PREFER lookup using List[str] or Tuple[str, ...]",
                    )
                )
            raise KeyError(err_msg) from e
    return cur_val
jsonbourne.core.JsonObj.eject() -> Dict[_KT, _VT] ⚓︎

Eject to python-builtin dictionary object

Examples:

>>> d = JsonObj(**{'uno': 'ONE', 'tres': 3, 'dos': 2})
>>> d
JsonObj(**{'uno': 'ONE', 'tres': 3, 'dos': 2})
>>> plain_ol_dict = d.eject()
>>> plain_ol_dict
{'uno': 'ONE', 'tres': 3, 'dos': 2}
>>> type(plain_ol_dict)
<class 'dict'>
Source code in libs/jsonbourne/jsonbourne/core.py
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
def eject(self) -> Dict[_KT, _VT]:
    """Eject to python-builtin dictionary object

    Examples:
        >>> d = JsonObj(**{'uno': 'ONE', 'tres': 3, 'dos': 2})
        >>> d
        JsonObj(**{'uno': 'ONE', 'tres': 3, 'dos': 2})
        >>> plain_ol_dict = d.eject()
        >>> plain_ol_dict
        {'uno': 'ONE', 'tres': 3, 'dos': 2}
        >>> type(plain_ol_dict)
        <class 'dict'>

    """
    try:
        return {k: unjsonify(v) for k, v in self._data.items()}
    except RecursionError as re:
        raise ValueError(
            "JSON.stringify recursion err; cycle/circular-refs detected"
        ) from re
jsonbourne.core.JsonObj.entries() -> ItemsView[_KT, _VT] ⚓︎

Alias for items

Source code in libs/jsonbourne/jsonbourne/core.py
434
435
436
def entries(self) -> ItemsView[_KT, _VT]:
    """Alias for items"""
    return self.items()
jsonbourne.core.JsonObj.filter_false(recursive: bool = False) -> JsonObj[_VT] ⚓︎

Filter key-values where the value is false-y

Parameters:

Name Type Description Default
recursive bool

Recurse into sub JsonObjs and dictionaries

False

Returns:

Type Description
JsonObj[_VT]

JsonObj that has been filtered

Examples:

>>> d = {
...     'falsey_dict': {},
...     'falsey_list': [],
...     'falsey_string': '',
...     'is_false': False,
...     'a': None,
...     'b': 2,
...     'c': {
...         'd': 'herm',
...         'e': None,
...         'falsey_dict': {},
...         'falsey_list': [],
...         'falsey_string': '',
...         'is_false': False,
...     },
...     }
...
>>> d = JsonObj(d)
>>> print(d)
JsonObj(**{
    'a': None,
    'b': 2,
    'c': {'d': 'herm',
          'e': None,
          'falsey_dict': {},
          'falsey_list': [],
          'falsey_string': '',
          'is_false': False},
    'falsey_dict': {},
    'falsey_list': [],
    'falsey_string': '',
    'is_false': False
})
>>> print(d.filter_false())
JsonObj(**{
    'b': 2,
    'c': {'d': 'herm',
          'e': None,
          'falsey_dict': {},
          'falsey_list': [],
          'falsey_string': '',
          'is_false': False}
})
>>> print(d.filter_false(recursive=True))
JsonObj(**{
    'b': 2, 'c': {'d': 'herm'}
})
Source code in libs/jsonbourne/jsonbourne/core.py
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
def filter_false(self, recursive: bool = False) -> JsonObj[_VT]:
    """Filter key-values where the value is false-y

    Args:
        recursive (bool): Recurse into sub JsonObjs and dictionaries

    Returns:
        JsonObj that has been filtered

    Examples:
        >>> d = {
        ...     'falsey_dict': {},
        ...     'falsey_list': [],
        ...     'falsey_string': '',
        ...     'is_false': False,
        ...     'a': None,
        ...     'b': 2,
        ...     'c': {
        ...         'd': 'herm',
        ...         'e': None,
        ...         'falsey_dict': {},
        ...         'falsey_list': [],
        ...         'falsey_string': '',
        ...         'is_false': False,
        ...     },
        ...     }
        ...
        >>> d = JsonObj(d)
        >>> print(d)
        JsonObj(**{
            'a': None,
            'b': 2,
            'c': {'d': 'herm',
                  'e': None,
                  'falsey_dict': {},
                  'falsey_list': [],
                  'falsey_string': '',
                  'is_false': False},
            'falsey_dict': {},
            'falsey_list': [],
            'falsey_string': '',
            'is_false': False
        })
        >>> print(d.filter_false())
        JsonObj(**{
            'b': 2,
            'c': {'d': 'herm',
                  'e': None,
                  'falsey_dict': {},
                  'falsey_list': [],
                  'falsey_string': '',
                  'is_false': False}
        })
        >>> print(d.filter_false(recursive=True))
        JsonObj(**{
            'b': 2, 'c': {'d': 'herm'}
        })

    """
    if recursive:
        return JsonObj(
            cast(
                Dict[str, _VT],
                {
                    k: (
                        v
                        if not isinstance(v, (dict, JsonObj))
                        else JsonObj(v).filter_false(recursive=True)
                    )
                    for k, v in self.items()
                    if v
                },
            )
        )
    return JsonObj({k: v for k, v in self.items() if v})
jsonbourne.core.JsonObj.filter_none(recursive: bool = False) -> JsonObj[_VT] ⚓︎

Filter key-values where the value is None but not false-y

Parameters:

Name Type Description Default
recursive bool

Recursively filter out None values

False

Returns:

Type Description
JsonObj[_VT]

JsonObj that has been filtered of None values

Examples:

>>> d = {
...     'falsey_dict': {},
...     'falsey_list': [],
...     'falsey_string': '',
...     'is_false': False,
...     'a': None,
...     'b': 2,
...     'c': {
...         'd': 'herm',
...         'e': None,
...         'falsey_dict': {},
...         'falsey_list': [],
...         'falsey_string': '',
...         'is_false': False,
...     },
...     }
...
>>> d = JsonObj(d)
>>> print(d)
JsonObj(**{
    'a': None,
    'b': 2,
    'c': {'d': 'herm',
          'e': None,
          'falsey_dict': {},
          'falsey_list': [],
          'falsey_string': '',
          'is_false': False},
    'falsey_dict': {},
    'falsey_list': [],
    'falsey_string': '',
    'is_false': False
})
>>> print(d.filter_none())
JsonObj(**{
    'b': 2,
    'c': {'d': 'herm',
          'e': None,
          'falsey_dict': {},
          'falsey_list': [],
          'falsey_string': '',
          'is_false': False},
    'falsey_dict': {},
    'falsey_list': [],
    'falsey_string': '',
    'is_false': False
})
>>> from pprint import pprint
>>> print(d.filter_none(recursive=True))
JsonObj(**{
    'b': 2,
    'c': {'d': 'herm',
          'falsey_dict': {},
          'falsey_list': [],
          'falsey_string': '',
          'is_false': False},
    'falsey_dict': {},
    'falsey_list': [],
    'falsey_string': '',
    'is_false': False
})
Source code in libs/jsonbourne/jsonbourne/core.py
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
def filter_none(self, recursive: bool = False) -> JsonObj[_VT]:
    """Filter key-values where the value is `None` but not false-y

    Args:
        recursive (bool): Recursively filter out None values

    Returns:
        JsonObj that has been filtered of None values

    Examples:
        >>> d = {
        ...     'falsey_dict': {},
        ...     'falsey_list': [],
        ...     'falsey_string': '',
        ...     'is_false': False,
        ...     'a': None,
        ...     'b': 2,
        ...     'c': {
        ...         'd': 'herm',
        ...         'e': None,
        ...         'falsey_dict': {},
        ...         'falsey_list': [],
        ...         'falsey_string': '',
        ...         'is_false': False,
        ...     },
        ...     }
        ...
        >>> d = JsonObj(d)
        >>> print(d)
        JsonObj(**{
            'a': None,
            'b': 2,
            'c': {'d': 'herm',
                  'e': None,
                  'falsey_dict': {},
                  'falsey_list': [],
                  'falsey_string': '',
                  'is_false': False},
            'falsey_dict': {},
            'falsey_list': [],
            'falsey_string': '',
            'is_false': False
        })
        >>> print(d.filter_none())
        JsonObj(**{
            'b': 2,
            'c': {'d': 'herm',
                  'e': None,
                  'falsey_dict': {},
                  'falsey_list': [],
                  'falsey_string': '',
                  'is_false': False},
            'falsey_dict': {},
            'falsey_list': [],
            'falsey_string': '',
            'is_false': False
        })
        >>> from pprint import pprint
        >>> print(d.filter_none(recursive=True))
        JsonObj(**{
            'b': 2,
            'c': {'d': 'herm',
                  'falsey_dict': {},
                  'falsey_list': [],
                  'falsey_string': '',
                  'is_false': False},
            'falsey_dict': {},
            'falsey_list': [],
            'falsey_string': '',
            'is_false': False
        })

    """
    if recursive:
        return JsonObj(
            cast(
                Dict[str, _VT],
                {
                    k: (
                        v
                        if not isinstance(v, (dict, JsonObj))
                        else JsonObj(v).filter_none(recursive=True)
                    )
                    for k, v in self.items()
                    if v is not None  # type: ignore[redundant-expr]
                },
            )
        )
    return JsonObj({k: v for k, v in self.items() if v is not None})  # type: ignore[redundant-expr]
jsonbourne.core.JsonObj.from_dict(data: Dict[_KT, _VT]) -> JsonObj[_VT] classmethod ⚓︎

Return a JsonObj object from a dictionary of data

Source code in libs/jsonbourne/jsonbourne/core.py
898
899
900
901
@classmethod
def from_dict(cls: Type[JsonObj[_VT]], data: Dict[_KT, _VT]) -> JsonObj[_VT]:
    """Return a JsonObj object from a dictionary of data"""
    return cls(**data)
jsonbourne.core.JsonObj.from_json(json_string: Union[bytes, str]) -> JsonObj[_VT] classmethod ⚓︎

Return a JsonObj object from a json string

Parameters:

Name Type Description Default
json_string str

JSON string to convert to a JsonObj

required

Returns:

Name Type Description
JsonObjT JsonObj[_VT]

JsonObj object for the given JSON string

Source code in libs/jsonbourne/jsonbourne/core.py
903
904
905
906
907
908
909
910
911
912
913
914
915
916
@classmethod
def from_json(
    cls: Type[JsonObj[_VT]], json_string: Union[bytes, str]
) -> JsonObj[_VT]:
    """Return a JsonObj object from a json string

    Args:
        json_string (str): JSON string to convert to a JsonObj

    Returns:
        JsonObjT: JsonObj object for the given JSON string

    """
    return cls._from_json(json_string)
jsonbourne.core.JsonObj.items() -> ItemsView[_KT, _VT] ⚓︎

Return an items view of the JsonObj object

Source code in libs/jsonbourne/jsonbourne/core.py
430
431
432
def items(self) -> ItemsView[_KT, _VT]:
    """Return an items view of the JsonObj object"""
    return self._data.items()
jsonbourne.core.JsonObj.keys() -> KeysView[_KT] ⚓︎

Return the keys view of the JsonObj object

Source code in libs/jsonbourne/jsonbourne/core.py
438
439
440
def keys(self) -> KeysView[_KT]:
    """Return the keys view of the JsonObj object"""
    return self._data.keys()
jsonbourne.core.JsonObj.recurse() -> None ⚓︎

Recursively convert all sub dictionaries to JsonObj objects

Source code in libs/jsonbourne/jsonbourne/core.py
256
257
258
def recurse(self) -> None:
    """Recursively convert all sub dictionaries to JsonObj objects"""
    self._data.update({k: jsonify(v) for k, v in self._data.items()})
jsonbourne.core.JsonObj.stringify(fmt: bool = False, pretty: bool = False, sort_keys: bool = False, append_newline: bool = False, default: Optional[Callable[[Any], Any]] = None, **kwargs: Any) -> str ⚓︎

Return JSON string of the JsonObj object (and children)

    Args:
        fmt (bool): If True, return a JSON string with newlines and indentation
        pretty (bool): If True, return a JSON string with newlines and indentation
        sort_keys (bool): Sort dictionary keys if True
        append_newline (bool): Append a newline '

' to JSON string if True default: default function hook for JSON serialization **kwargs (Any): additional kwargs to be passed down to jsonlib.dumps

    Returns:
        str: JSON string of the JsonObj object
Source code in libs/jsonbourne/jsonbourne/core.py
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
def stringify(
    self,
    fmt: bool = False,
    pretty: bool = False,
    sort_keys: bool = False,
    append_newline: bool = False,
    default: Optional[Callable[[Any], Any]] = None,
    **kwargs: Any,
) -> str:
    """Return JSON string of the JsonObj object (and children)

    Args:
        fmt (bool): If True, return a JSON string with newlines and indentation
        pretty (bool): If True, return a JSON string with newlines and indentation
        sort_keys (bool): Sort dictionary keys if True
        append_newline (bool): Append a newline '\n' to JSON string if True
        default: default function hook for JSON serialization
        **kwargs (Any): additional kwargs to be passed down to jsonlib.dumps

    Returns:
        str: JSON string of the JsonObj object

    """
    return self._to_json(
        fmt=fmt,
        pretty=pretty,
        sort_keys=sort_keys,
        append_newline=append_newline,
        default=default,
        **kwargs,
    )
jsonbourne.core.JsonObj.to_dict() -> Dict[_KT, Any] ⚓︎

Return the JsonObj object (and children) as a python dictionary

Source code in libs/jsonbourne/jsonbourne/core.py
890
891
892
def to_dict(self) -> Dict[_KT, Any]:
    """Return the JsonObj object (and children) as a python dictionary"""
    return self.eject()
jsonbourne.core.JsonObj.to_json(fmt: bool = False, pretty: bool = False, sort_keys: bool = False, append_newline: bool = False, default: Optional[Callable[[Any], Any]] = None, **kwargs: Any) -> str ⚓︎

Return JSON string of the JsonObj object (and children)

    Args:
        fmt (bool): If True, return a JSON string with newlines and indentation
        pretty (bool): If True, return a JSON string with newlines and indentation
        sort_keys (bool): Sort dictionary keys if True
        append_newline (bool): Append a newline '

' to JSON string if True default: default function hook for JSON serialization **kwargs (Any): additional kwargs to be passed down to jsonlib.dumps

    Returns:
        str: JSON string of the JsonObj object
Source code in libs/jsonbourne/jsonbourne/core.py
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
def to_json(
    self,
    fmt: bool = False,
    pretty: bool = False,
    sort_keys: bool = False,
    append_newline: bool = False,
    default: Optional[Callable[[Any], Any]] = None,
    **kwargs: Any,
) -> str:
    """Return JSON string of the JsonObj object (and children)

    Args:
        fmt (bool): If True, return a JSON string with newlines and indentation
        pretty (bool): If True, return a JSON string with newlines and indentation
        sort_keys (bool): Sort dictionary keys if True
        append_newline (bool): Append a newline '\n' to JSON string if True
        default: default function hook for JSON serialization
        **kwargs (Any): additional kwargs to be passed down to jsonlib.dumps

    Returns:
        str: JSON string of the JsonObj object

    """
    return self._to_json(
        fmt=fmt,
        pretty=pretty,
        sort_keys=sort_keys,
        append_newline=append_newline,
        default=default,
        **kwargs,
    )
jsonbourne.core.JsonObj.to_str(minify: bool = False, width: Optional[int] = None) -> str ⚓︎

Return a string representation of the JsonObj object

Source code in libs/jsonbourne/jsonbourne/core.py
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
def to_str(self, minify: bool = False, width: Optional[int] = None) -> str:
    """Return a string representation of the JsonObj object"""
    if minify:
        return type(self).__name__ + "(**" + str(self.to_dict()) + ")"
    if not bool(self._data):
        return f"{type(self).__name__}(**{{}})"
    _width = get_terminal_size(fallback=(88, 24)).columns - 12
    return "".join(
        [
            type(self).__name__,
            "(**{\n    ",
            pformat(self.eject(), width=_width)[1:-1].replace("\n", "\n   "),
            "\n})",
        ]
    ).replace("JsonObj(**{}),", "{},")
jsonbourne.core.JsonObj.validate_type(val: Any) -> JsonObj[_VT] classmethod ⚓︎

Validate and convert a value to a JsonObj object

Source code in libs/jsonbourne/jsonbourne/core.py
1064
1065
1066
1067
@classmethod
def validate_type(cls: Type[JsonObj[_VT]], val: Any) -> JsonObj[_VT]:
    """Validate and convert a value to a JsonObj object"""
    return cls(val)
Functions⚓︎
jsonbourne.core.is_float(value: Any) -> bool ⚓︎

Return True if value is a float

Source code in libs/jsonbourne/jsonbourne/core.py
111
112
113
114
115
116
117
118
def is_float(value: Any) -> bool:
    """Return True if value is a float"""
    try:
        float(value)
        return True
    except ValueError:
        pass
    return False
jsonbourne.core.is_identifier(string: str) -> bool ⚓︎

Return True if a string is a valid python identifier; False otherwise

Parameters:

Name Type Description Default
string str

String (likely to be used as a key) to check

required

Returns:

Name Type Description
bool bool

True if is an identifier

Examples:

>>> is_identifier("herm")
True
>>> is_identifier("something that contains spaces")
False
>>> is_identifier("import")
False
>>> is_identifier("something.with.periods")
False
>>> is_identifier("astring-with-dashes")
False
>>> is_identifier("astring_with_underscores")
True
>>> is_identifier(123)
False
Source code in libs/jsonbourne/jsonbourne/core.py
 76
 77
 78
 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
def is_identifier(string: str) -> bool:
    """Return True if a string is a valid python identifier; False otherwise

    Args:
        string (str): String (likely to be used as a key) to check

    Returns:
        bool: True if is an identifier

    Examples:
        >>> is_identifier("herm")
        True
        >>> is_identifier("something that contains spaces")
        False
        >>> is_identifier("import")
        False
        >>> is_identifier("something.with.periods")
        False
        >>> is_identifier("astring-with-dashes")
        False
        >>> is_identifier("astring_with_underscores")
        True
        >>> is_identifier(123)
        False

    """
    try:
        assert isinstance(string, str)
    except AssertionError:
        return False
    if not string.isidentifier():
        return False
    return not keyword.iskeyword(string)
jsonbourne.core.is_int(value: Any) -> bool ⚓︎

Return True if value is a int

Source code in libs/jsonbourne/jsonbourne/core.py
121
122
123
124
125
126
127
128
129
130
def is_int(value: Any) -> bool:
    """Return True if value is a int"""
    if isinstance(value, int):
        return True
    if isinstance(value, float):
        return value.is_integer()
    _value: str = str(value)
    if _value[0] in ("-", "+"):
        return str(_value[1:]).isdigit()
    return _value.isdigit()
jsonbourne.core.is_number(value: Any) -> bool ⚓︎

Return True if value is a number

Source code in libs/jsonbourne/jsonbourne/core.py
133
134
135
def is_number(value: Any) -> bool:
    """Return True if value is a number"""
    return is_int(value) or is_float(value)
jsonbourne.core.is_pydantic_model(cls: Any) -> bool ⚓︎

Return True if cls is a pydantic model

Source code in libs/jsonbourne/jsonbourne/core.py
138
139
140
def is_pydantic_model(cls: Any) -> bool:
    """Return True if cls is a pydantic model"""
    return hasattr(cls, "model_fields") or hasattr(cls, "__fields__")
jsonbourne.core.jsonify(value: Any) -> Any ⚓︎

Convert and return a value to a JsonObj if the value is a dict

Source code in libs/jsonbourne/jsonbourne/core.py
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
def jsonify(value: Any) -> Any:
    """Convert and return a value to a JsonObj if the value is a dict"""
    if isinstance(value, (JsonObj, JsonDict)) or issubclass(value.__class__, JsonObj):
        return value
    if isinstance(value, dict) and not isinstance(value, JsonObj):
        return JsonObj(value)
    if isinstance(value, list):
        return [jsonify(el) for el in value]
    if isinstance(value, tuple):
        return tuple([jsonify(el) for el in value])
    if isinstance(value, str):
        try:
            data = jsonlib.loads(value)
            return jsonify(data)
        except Exception:
            pass

    return value
jsonbourne.core.unjsonify(value: Any) -> Any ⚓︎

Recursively eject a JsonDit object

Source code in libs/jsonbourne/jsonbourne/core.py
1129
1130
1131
1132
1133
1134
1135
1136
1137
def unjsonify(value: Any) -> Any:
    """Recursively eject a JsonDit object"""
    if isinstance(value, JsonObj):
        return value._data
    if isinstance(value, list):
        return [unjsonify(el) for el in value]
    if isinstance(value, tuple):
        return tuple([unjsonify(el) for el in value])
    return value
Modules⚓︎

jsonbourne.dev ⚓︎

jsonbourne.dev

jsonbourne.fastapi ⚓︎

Classes⚓︎
jsonbourne.fastapi.JSONBOURNEResponse ⚓︎

Bases: Response

FastAPI/starlette json response to auto use jsonbourne

Functions⚓︎
jsonbourne.fastapi.JSONBOURNEResponse.render(content: Any) -> bytes ⚓︎

Return JSON string for content as bytes

Source code in libs/jsonbourne/jsonbourne/fastapi.py
28
29
30
def render(self, content: Any) -> bytes:
    """Return JSON string for content as bytes"""
    return JSON.binify(data=content)

jsonbourne.helpers ⚓︎

JSONBourne helper funks and utils

Functions⚓︎
jsonbourne.helpers.rm_js_comments(string: str) -> str ⚓︎

Rejects/regex that removes js/ts/json style comments

Source (stackoverflow): https://stackoverflow.com/a/18381470

Source code in libs/jsonbourne/jsonbourne/helpers.py
23
24
25
26
27
28
29
30
31
32
33
def rm_js_comments(string: str) -> str:
    """Rejects/regex that removes js/ts/json style comments

    Source (stackoverflow):
        https://stackoverflow.com/a/18381470
    """
    # first group captures quoted strings (double or single)
    # second group captures comments (//single-line or /* multi-line */)
    regex = re.compile(STRIP_JSON_COMMENTS_REGEX, re.MULTILINE | re.DOTALL)

    return regex.sub(_strip_json_comments_regex_replacer, string)

jsonbourne.httpx ⚓︎

Jsonbourne wrapper around httpx clients -- lets you do response.JSON()

Functions⚓︎
jsonbourne.httpx.patch_httpx() -> None ⚓︎

Patch httpx to add a .JSON() method to Response objects.

Source code in libs/jsonbourne/jsonbourne/httpx.py
26
27
28
def patch_httpx() -> None:
    """Patch httpx to add a .JSON() method to Response objects."""
    Response.JSON = _JSON  # type: ignore[attr-defined]

jsonbourne.json_arr ⚓︎

Classes⚓︎
jsonbourne.json_arr.JsonArr(iterable: Optional[Iterable[_T]] = None) ⚓︎

Bases: MutableSequence[_T], Generic[_T]

Source code in libs/jsonbourne/jsonbourne/json_arr.py
69
70
def __init__(self, iterable: Optional[Iterable[_T]] = None) -> None:
    self.__arr = list(iterable or [])
Functions⚓︎
jsonbourne.json_arr.JsonArr.__get_type_validator__(source_type: Any, handler: GetCoreSchemaHandler) -> Iterator[Callable[[Any], Any]] classmethod ⚓︎

Return the JsonObj validator functions

Source code in libs/jsonbourne/jsonbourne/json_arr.py
218
219
220
221
222
223
@classmethod
def __get_type_validator__(
    cls, source_type: Any, handler: GetCoreSchemaHandler
) -> Iterator[Callable[[Any], Any]]:
    """Return the JsonObj validator functions"""
    yield cls.validate_type
jsonbourne.json_arr.JsonArr.__post_init__() -> Any ⚓︎

Function place holder that is called after object initialization

Source code in libs/jsonbourne/jsonbourne/json_arr.py
72
73
def __post_init__(self) -> Any:
    """Function place holder that is called after object initialization"""
jsonbourne.json_arr.JsonArr.slice(start: Optional[int] = None, end: Optional[int] = None) -> JsonArr[_T] ⚓︎

Return a slice as new jsonarray

Parameters:

Name Type Description Default
start Optional[int]

start index. Defaults to None.

None
end Optional[int]

end index. Defaults to None.

None

Returns:

Type Description
JsonArr[_T]

JsonArr[_T]: new JsonArr

Examples:

>>> arr = JsonArr([1, 2, 3, 4, 5])
>>> arr.slice()
JsonArr([1, 2, 3, 4, 5])
>>> arr.slice(1, 3)
JsonArr([2, 3])
Source code in libs/jsonbourne/jsonbourne/json_arr.py
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
def slice(
    self, start: Optional[int] = None, end: Optional[int] = None
) -> JsonArr[_T]:
    """Return a slice as new jsonarray

    Args:
        start (Optional[int], optional): start index. Defaults to None.
        end (Optional[int], optional): end index. Defaults to None.

    Returns:
        JsonArr[_T]: new JsonArr

    Examples:
        >>> arr = JsonArr([1, 2, 3, 4, 5])
        >>> arr.slice()
        JsonArr([1, 2, 3, 4, 5])
        >>> arr.slice(1, 3)
        JsonArr([2, 3])

    """
    if start is None and end is None:
        return JsonArr([*self.__arr])
    _start = 0 if start is None else start
    _end = len(self) if end is None else end
    return JsonArr(self.__arr[_start:_end])
jsonbourne.json_arr.JsonArr.validate_type(val: Any) -> JsonArr[_T] classmethod ⚓︎

Validate and convert a value to a JsonObj object

Source code in libs/jsonbourne/jsonbourne/json_arr.py
213
214
215
216
@classmethod
def validate_type(cls: Type[JsonArr[_T]], val: Any) -> JsonArr[_T]:
    """Validate and convert a value to a JsonObj object"""
    return cls(val)

jsonbourne.jsonlib ⚓︎

jsonbourne jsonlib api

Classes⚓︎
jsonbourne.jsonlib.JsonLibABC ⚓︎

Bases: ABC

Functions⚓︎
jsonbourne.jsonlib.JsonLibABC.default(obj: Any) -> Any staticmethod ⚓︎

Default encoder

Source code in libs/jsonbourne/jsonbourne/jsonlib.py
146
147
148
149
@staticmethod
def default(obj: Any) -> Any:
    """Default encoder"""
    return _json_encode_default(obj)

jsonbourne.pydantic ⚓︎

JSONBourne + Pydantic

Classes⚓︎
jsonbourne.pydantic.JsonBaseConfig ⚓︎

Pydantic v1 model config class for JsonBaseModel; can be overridden

jsonbourne.pydantic.JsonBaseModel(*args: Any, **kwargs: _VT) ⚓︎

Bases: BaseModel, JsonObj, MutableMapping

Hybrid pydantic.BaseModel and jsonbourne.JsonObj

Source code in libs/jsonbourne/jsonbourne/core.py
242
243
244
245
246
247
248
249
250
251
252
253
254
def __init__(
    self,
    *args: Any,
    **kwargs: _VT,
) -> None:
    """Use the object dict"""
    _data = dict(*args, **kwargs)
    super().__setattr__("_data", _data)
    if not all(isinstance(k, str) for k in self._data):
        d = {k: v for k, v in self._data.items() if not isinstance(k, str)}  # type: ignore[redundant-expr]
        raise ValueError(f"JsonObj keys MUST be strings! Bad key values: {str(d)}")
    self.recurse()
    self.__post_init__()
Attributes⚓︎
jsonbourne.pydantic.JsonBaseModel.__property_fields__: Set[str] property ⚓︎

Returns a set of property names for the class that have a setter

Functions⚓︎
jsonbourne.pydantic.JsonBaseModel.__contains__(key: _KT) -> bool ⚓︎

Check if a key or dot-key is contained within the JsonObj object

Parameters:

Name Type Description Default
key _KT

root level key or a dot-key

required

Returns:

Name Type Description
bool bool

True if the key/dot-key is in the JsonObj; False otherwise

Examples:

>>> d = {"uno": 1, "dos": 2, "tres": 3, "sub": {"a": 1, "b": 2, "c": [3, 4, 5, 6], "d": "a_string"}}
>>> d = JsonObj(d)
>>> d
JsonObj(**{'uno': 1, 'dos': 2, 'tres': 3, 'sub': {'a': 1, 'b': 2, 'c': [3, 4, 5, 6], 'd': 'a_string'}})
>>> 'uno' in d
True
>>> 'this_key_is_not_in_d' in d
False
>>> 'sub.a' in d
True
>>> 'sub.d.a' in d
False
Source code in libs/jsonbourne/jsonbourne/core.py
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
def __contains__(self, key: _KT) -> bool:  # type: ignore[override]
    """Check if a key or dot-key is contained within the JsonObj object

    Args:
        key (_KT): root level key or a dot-key

    Returns:
        bool: True if the key/dot-key is in the JsonObj; False otherwise

    Examples:
        >>> d = {"uno": 1, "dos": 2, "tres": 3, "sub": {"a": 1, "b": 2, "c": [3, 4, 5, 6], "d": "a_string"}}
        >>> d = JsonObj(d)
        >>> d
        JsonObj(**{'uno': 1, 'dos': 2, 'tres': 3, 'sub': {'a': 1, 'b': 2, 'c': [3, 4, 5, 6], 'd': 'a_string'}})
        >>> 'uno' in d
        True
        >>> 'this_key_is_not_in_d' in d
        False
        >>> 'sub.a' in d
        True
        >>> 'sub.d.a' in d
        False

    """
    if "." in key:
        first_key, _, rest = key.partition(".")
        val = self._data.get(first_key)
        return isinstance(val, MutableMapping) and val.__contains__(rest)
    return key in self._data
jsonbourne.pydantic.JsonBaseModel.__get_type_validator__(source_type: Any, handler: GetCoreSchemaHandler) -> Iterator[Callable[[Any], Any]] classmethod ⚓︎

Return the JsonObj validator functions

Source code in libs/jsonbourne/jsonbourne/core.py
1069
1070
1071
1072
1073
1074
@classmethod
def __get_type_validator__(
    cls, source_type: Any, handler: GetCoreSchemaHandler
) -> Iterator[Callable[[Any], Any]]:
    """Return the JsonObj validator functions"""
    yield cls.validate_type
jsonbourne.pydantic.JsonBaseModel.__getattr__(item: _KT) -> Any ⚓︎

Return an attr

Examples:

>>> d = {
...     'falsey_dict': {},
...     'falsey_list': [],
...     'falsey_string': '',
...     'is_false': False,
...     'a': None,
...     'b': 2,
...     'c': {
...         'd': 'herm',
...         'e': None,
...         'falsey_dict': {},
...         'falsey_list': [],
...         'falsey_string': '',
...         'is_false': False,
...     },
...     }
...
>>> d = JsonObj(d)
>>> d.__getattr__('b')
2
>>> d.b
2
Source code in libs/jsonbourne/jsonbourne/core.py
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
def __getattr__(self, item: _KT) -> Any:
    """Return an attr

    Examples:
        >>> d = {
        ...     'falsey_dict': {},
        ...     'falsey_list': [],
        ...     'falsey_string': '',
        ...     'is_false': False,
        ...     'a': None,
        ...     'b': 2,
        ...     'c': {
        ...         'd': 'herm',
        ...         'e': None,
        ...         'falsey_dict': {},
        ...         'falsey_list': [],
        ...         'falsey_string': '',
        ...         'is_false': False,
        ...     },
        ...     }
        ...
        >>> d = JsonObj(d)
        >>> d.__getattr__('b')
        2
        >>> d.b
        2

    """
    if item == "_data":
        try:
            return object.__getattribute__(self, "_data")
        except AttributeError:
            return self.__dict__
    if item in _JsonObjMutableMapping_attrs or item in self._cls_protected_attrs():
        return object.__getattribute__(self, item)
    try:
        return jsonify(self.__getitem__(str(item)))
    except KeyError:
        pass
    return object.__getattribute__(self, item)
jsonbourne.pydantic.JsonBaseModel.__post_init__() -> Any ⚓︎

Function place holder that is called after object initialization

Source code in libs/jsonbourne/jsonbourne/pydantic.py
98
99
def __post_init__(self) -> Any:
    """Function place holder that is called after object initialization"""
jsonbourne.pydantic.JsonBaseModel.__setitem__(key: _KT, value: _VT) -> None ⚓︎

Set JsonObj item with 'key' to 'value'

Parameters:

Name Type Description Default
key _KT

Key/item to set

required
value _VT

Value to set

required

Returns:

Type Description
None

None

Raises:

Type Description
ValueError

If given a key that is not a valid python keyword/identifier

Examples:

>>> d = JsonObj()
>>> d.a = 123
>>> d['b'] = 321
>>> d
JsonObj(**{'a': 123, 'b': 321})
>>> d[123] = 'a'
>>> d
JsonObj(**{'a': 123, 'b': 321, '123': 'a'})
>>> d['456'] = 'a'
>>> d
JsonObj(**{'a': 123, 'b': 321, '123': 'a', '456': 'a'})
Source code in libs/jsonbourne/jsonbourne/core.py
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
def __setitem__(self, key: _KT, value: _VT) -> None:
    """Set JsonObj item with 'key' to 'value'

    Args:
        key (_KT): Key/item to set
        value: Value to set

    Returns:
        None

    Raises:
        ValueError: If given a key that is not a valid python keyword/identifier

    Examples:
        >>> d = JsonObj()
        >>> d.a = 123
        >>> d['b'] = 321
        >>> d
        JsonObj(**{'a': 123, 'b': 321})
        >>> d[123] = 'a'
        >>> d
        JsonObj(**{'a': 123, 'b': 321, '123': 'a'})
        >>> d['456'] = 'a'
        >>> d
        JsonObj(**{'a': 123, 'b': 321, '123': 'a', '456': 'a'})

    """
    self.__setitem(key, value, identifier=False)
jsonbourne.pydantic.JsonBaseModel.asdict() -> Dict[_KT, Any] ⚓︎

Return the JsonObj object (and children) as a python dictionary

Source code in libs/jsonbourne/jsonbourne/core.py
894
895
896
def asdict(self) -> Dict[_KT, Any]:
    """Return the JsonObj object (and children) as a python dictionary"""
    return self.eject()
jsonbourne.pydantic.JsonBaseModel.defaults_dict() -> Dict[str, Any] classmethod ⚓︎

Return a dictionary of non-required keys -> default value(s)

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: Dictionary of non-required keys -> default value

Examples:

>>> class Thing(JsonBaseModel):
...     a: int = 1
...     b: str = "herm"
...
>>> t = Thing()
>>> t
Thing(a=1, b='herm')
>>> t.to_dict_filter_defaults()
{}
>>> t.to_json_obj_filter_defaults()
JsonObj(**{})
>>> t = Thing(a=123)
>>> t
Thing(a=123, b='herm')
>>> t.to_dict_filter_defaults()
{'a': 123}
>>> t.to_json_obj_filter_defaults()
JsonObj(**{'a': 123})
>>> t.defaults_dict()
{'a': 1, 'b': 'herm'}
Source code in libs/jsonbourne/jsonbourne/pydantic.py
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
@classmethod
def defaults_dict(cls) -> Dict[str, Any]:
    """Return a dictionary of non-required keys -> default value(s)

    Returns:
        Dict[str, Any]: Dictionary of non-required keys -> default value

    Examples:
        >>> class Thing(JsonBaseModel):
        ...     a: int = 1
        ...     b: str = "herm"
        ...
        >>> t = Thing()
        >>> t
        Thing(a=1, b='herm')
        >>> t.to_dict_filter_defaults()
        {}
        >>> t.to_json_obj_filter_defaults()
        JsonObj(**{})
        >>> t = Thing(a=123)
        >>> t
        Thing(a=123, b='herm')
        >>> t.to_dict_filter_defaults()
        {'a': 123}
        >>> t.to_json_obj_filter_defaults()
        JsonObj(**{'a': 123})
        >>> t.defaults_dict()
        {'a': 1, 'b': 'herm'}

    """
    return {
        k: v.default for k, v in cls.model_fields.items() if not v.is_required()
    }
jsonbourne.pydantic.JsonBaseModel.dict(*args: Any, **kwargs: Any) -> Dict[str, Any] ⚓︎

Alias for model_dump

Source code in libs/jsonbourne/jsonbourne/pydantic.py
118
119
120
def dict(self, *args: Any, **kwargs: Any) -> Dict[str, Any]:
    """Alias for `model_dump`"""
    return self.model_dump(*args, **kwargs)
jsonbourne.pydantic.JsonBaseModel.dot_items() -> Iterator[Tuple[Tuple[str, ...], _VT]] ⚓︎

Yield tuples of the form (dot-key, value)

OG-version

def dot_items(self) -> Iterator[Tuple[str, Any]]: return ((dk, self.dot_lookup(dk)) for dk in self.dot_keys())

Readable-version

for k, value in self.items(): value = jsonify(value) if isinstance(value, JsonObj) or hasattr(value, 'dot_items'): yield from ((f"{k}.{dk}", dv) for dk, dv in value.dot_items()) else: yield k, value

Source code in libs/jsonbourne/jsonbourne/core.py
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
def dot_items(self) -> Iterator[Tuple[Tuple[str, ...], _VT]]:
    """Yield tuples of the form (dot-key, value)

    OG-version:
        def dot_items(self) -> Iterator[Tuple[str, Any]]:
            return ((dk, self.dot_lookup(dk)) for dk in self.dot_keys())

    Readable-version:
        for k, value in self.items():
            value = jsonify(value)
            if isinstance(value, JsonObj) or hasattr(value, 'dot_items'):
                yield from ((f"{k}.{dk}", dv) for dk, dv in value.dot_items())
            else:
                yield k, value
    """

    return chain.from_iterable(
        (
            (
                (
                    *(
                        (
                            (
                                str(k),
                                *dk,
                            ),
                            dv,
                        )
                        for dk, dv in as_json_obj(v).dot_items()
                    ),
                )
                if isinstance(v, (JsonObj, dict))
                else (((str(k),), v),)
            )
            for k, v in self.items()
        )
    )
jsonbourne.pydantic.JsonBaseModel.dot_items_list() -> List[Tuple[Tuple[str, ...], Any]] ⚓︎

Return list of tuples of the form (dot-key, value)

Source code in libs/jsonbourne/jsonbourne/core.py
763
764
765
def dot_items_list(self) -> List[Tuple[Tuple[str, ...], Any]]:
    """Return list of tuples of the form (dot-key, value)"""
    return list(self.dot_items())
jsonbourne.pydantic.JsonBaseModel.dot_keys() -> Iterable[Tuple[str, ...]] ⚓︎

Yield the JsonObj's dot-notation keys

Returns:

Type Description
Iterable[Tuple[str, ...]]

Iterable[str]: List of the dot-notation friendly keys

The Non-chain version (shown below) is very slightly slower than the itertools.chain version.

NON-CHAIN VERSION:

for k, value in self.items(): value = jsonify(value) if isinstance(value, JsonObj): yield from (f"{k}.{dk}" for dk in value.dot_keys()) else: yield k

Source code in libs/jsonbourne/jsonbourne/core.py
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
def dot_keys(self) -> Iterable[Tuple[str, ...]]:
    """Yield the JsonObj's dot-notation keys

    Returns:
        Iterable[str]: List of the dot-notation friendly keys


    The Non-chain version (shown below) is very slightly slower than the
    `itertools.chain` version.

    NON-CHAIN VERSION:

    for k, value in self.items():
        value = jsonify(value)
        if isinstance(value, JsonObj):
            yield from (f"{k}.{dk}" for dk in value.dot_keys())
        else:
            yield k

    """
    return chain(
        *(
            (
                ((str(k),),)
                if not isinstance(v, JsonObj)
                else (*((str(k), *dk) for dk in jsonify(v).dot_keys()),)
            )
            for k, v in self.items()
        )
    )
jsonbourne.pydantic.JsonBaseModel.dot_keys_list(sort_keys: bool = False) -> List[Tuple[str, ...]] ⚓︎

Return a list of the JsonObj's dot-notation friendly keys

Parameters:

Name Type Description Default
sort_keys bool

Flag to have the dot-keys be returned sorted

False

Returns:

Type Description
List[Tuple[str, ...]]

List[str]: List of the dot-notation friendly keys

Source code in libs/jsonbourne/jsonbourne/core.py
660
661
662
663
664
665
666
667
668
669
670
671
672
def dot_keys_list(self, sort_keys: bool = False) -> List[Tuple[str, ...]]:
    """Return a list of the JsonObj's dot-notation friendly keys

    Args:
        sort_keys (bool): Flag to have the dot-keys be returned sorted

    Returns:
        List[str]: List of the dot-notation friendly keys

    """
    if sort_keys:
        return sorted(self.dot_keys_list())
    return list(self.dot_keys())
jsonbourne.pydantic.JsonBaseModel.dot_keys_set() -> Set[Tuple[str, ...]] ⚓︎

Return a set of the JsonObj's dot-notation friendly keys

Returns:

Type Description
Set[Tuple[str, ...]]

Set[str]: List of the dot-notation friendly keys

Source code in libs/jsonbourne/jsonbourne/core.py
674
675
676
677
678
679
680
681
def dot_keys_set(self) -> Set[Tuple[str, ...]]:
    """Return a set of the JsonObj's dot-notation friendly keys

    Returns:
        Set[str]: List of the dot-notation friendly keys

    """
    return set(self.dot_keys())
jsonbourne.pydantic.JsonBaseModel.dot_lookup(key: Union[str, Tuple[str, ...], List[str]]) -> Any ⚓︎

Look up JsonObj keys using dot notation as a string

Parameters:

Name Type Description Default
key str

dot-notation key to look up ('key1.key2.third_key')

required

Returns:

Type Description
Any

The result of the dot-notation key look up

Raises:

Type Description
KeyError

Raised if the dot-key is not in in the object

ValueError

Raised if key is not a str/Tuple[str, ...]/List[str]

Source code in libs/jsonbourne/jsonbourne/core.py
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
def dot_lookup(self, key: Union[str, Tuple[str, ...], List[str]]) -> Any:
    """Look up JsonObj keys using dot notation as a string

    Args:
        key (str): dot-notation key to look up ('key1.key2.third_key')

    Returns:
        The result of the dot-notation key look up

    Raises:
        KeyError: Raised if the dot-key is not in in the object
        ValueError: Raised if key is not a str/Tuple[str, ...]/List[str]

    """
    if not isinstance(key, (str, list, tuple)):
        raise ValueError(
            "".join(
                (
                    "dot_key arg must be string or sequence of strings; ",
                    "strings will be split on '.'",
                )
            )
        )
    parts = key.split(".") if isinstance(key, str) else list(key)
    root_val: Any = self._data[parts[0]]
    cur_val = root_val
    for ix, part in enumerate(parts[1:], start=1):
        try:
            cur_val = cur_val[part]
        except TypeError as e:
            reached = ".".join(parts[:ix])
            err_msg = f"Invalid DotKey: {key} -- Lookup reached: {reached} => {str(cur_val)}"
            if isinstance(key, str):
                err_msg += "".join(
                    (
                        f"\nNOTE!!! lookup performed with string ('{key}') ",
                        "PREFER lookup using List[str] or Tuple[str, ...]",
                    )
                )
            raise KeyError(err_msg) from e
    return cur_val
jsonbourne.pydantic.JsonBaseModel.eject() -> Dict[_KT, _VT] ⚓︎

Eject to python-builtin dictionary object

Examples:

>>> d = JsonObj(**{'uno': 'ONE', 'tres': 3, 'dos': 2})
>>> d
JsonObj(**{'uno': 'ONE', 'tres': 3, 'dos': 2})
>>> plain_ol_dict = d.eject()
>>> plain_ol_dict
{'uno': 'ONE', 'tres': 3, 'dos': 2}
>>> type(plain_ol_dict)
<class 'dict'>
Source code in libs/jsonbourne/jsonbourne/core.py
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
def eject(self) -> Dict[_KT, _VT]:
    """Eject to python-builtin dictionary object

    Examples:
        >>> d = JsonObj(**{'uno': 'ONE', 'tres': 3, 'dos': 2})
        >>> d
        JsonObj(**{'uno': 'ONE', 'tres': 3, 'dos': 2})
        >>> plain_ol_dict = d.eject()
        >>> plain_ol_dict
        {'uno': 'ONE', 'tres': 3, 'dos': 2}
        >>> type(plain_ol_dict)
        <class 'dict'>

    """
    try:
        return {k: unjsonify(v) for k, v in self._data.items()}
    except RecursionError as re:
        raise ValueError(
            "JSON.stringify recursion err; cycle/circular-refs detected"
        ) from re
jsonbourne.pydantic.JsonBaseModel.entries() -> ItemsView[_KT, _VT] ⚓︎

Alias for items

Source code in libs/jsonbourne/jsonbourne/core.py
434
435
436
def entries(self) -> ItemsView[_KT, _VT]:
    """Alias for items"""
    return self.items()
jsonbourne.pydantic.JsonBaseModel.filter_false(recursive: bool = False) -> JsonObj[_VT] ⚓︎

Filter key-values where the value is false-y

Parameters:

Name Type Description Default
recursive bool

Recurse into sub JsonObjs and dictionaries

False

Returns:

Type Description
JsonObj[_VT]

JsonObj that has been filtered

Examples:

>>> d = {
...     'falsey_dict': {},
...     'falsey_list': [],
...     'falsey_string': '',
...     'is_false': False,
...     'a': None,
...     'b': 2,
...     'c': {
...         'd': 'herm',
...         'e': None,
...         'falsey_dict': {},
...         'falsey_list': [],
...         'falsey_string': '',
...         'is_false': False,
...     },
...     }
...
>>> d = JsonObj(d)
>>> print(d)
JsonObj(**{
    'a': None,
    'b': 2,
    'c': {'d': 'herm',
          'e': None,
          'falsey_dict': {},
          'falsey_list': [],
          'falsey_string': '',
          'is_false': False},
    'falsey_dict': {},
    'falsey_list': [],
    'falsey_string': '',
    'is_false': False
})
>>> print(d.filter_false())
JsonObj(**{
    'b': 2,
    'c': {'d': 'herm',
          'e': None,
          'falsey_dict': {},
          'falsey_list': [],
          'falsey_string': '',
          'is_false': False}
})
>>> print(d.filter_false(recursive=True))
JsonObj(**{
    'b': 2, 'c': {'d': 'herm'}
})
Source code in libs/jsonbourne/jsonbourne/core.py
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
def filter_false(self, recursive: bool = False) -> JsonObj[_VT]:
    """Filter key-values where the value is false-y

    Args:
        recursive (bool): Recurse into sub JsonObjs and dictionaries

    Returns:
        JsonObj that has been filtered

    Examples:
        >>> d = {
        ...     'falsey_dict': {},
        ...     'falsey_list': [],
        ...     'falsey_string': '',
        ...     'is_false': False,
        ...     'a': None,
        ...     'b': 2,
        ...     'c': {
        ...         'd': 'herm',
        ...         'e': None,
        ...         'falsey_dict': {},
        ...         'falsey_list': [],
        ...         'falsey_string': '',
        ...         'is_false': False,
        ...     },
        ...     }
        ...
        >>> d = JsonObj(d)
        >>> print(d)
        JsonObj(**{
            'a': None,
            'b': 2,
            'c': {'d': 'herm',
                  'e': None,
                  'falsey_dict': {},
                  'falsey_list': [],
                  'falsey_string': '',
                  'is_false': False},
            'falsey_dict': {},
            'falsey_list': [],
            'falsey_string': '',
            'is_false': False
        })
        >>> print(d.filter_false())
        JsonObj(**{
            'b': 2,
            'c': {'d': 'herm',
                  'e': None,
                  'falsey_dict': {},
                  'falsey_list': [],
                  'falsey_string': '',
                  'is_false': False}
        })
        >>> print(d.filter_false(recursive=True))
        JsonObj(**{
            'b': 2, 'c': {'d': 'herm'}
        })

    """
    if recursive:
        return JsonObj(
            cast(
                Dict[str, _VT],
                {
                    k: (
                        v
                        if not isinstance(v, (dict, JsonObj))
                        else JsonObj(v).filter_false(recursive=True)
                    )
                    for k, v in self.items()
                    if v
                },
            )
        )
    return JsonObj({k: v for k, v in self.items() if v})
jsonbourne.pydantic.JsonBaseModel.filter_none(recursive: bool = False) -> JsonObj[_VT] ⚓︎

Filter key-values where the value is None but not false-y

Parameters:

Name Type Description Default
recursive bool

Recursively filter out None values

False

Returns:

Type Description
JsonObj[_VT]

JsonObj that has been filtered of None values

Examples:

>>> d = {
...     'falsey_dict': {},
...     'falsey_list': [],
...     'falsey_string': '',
...     'is_false': False,
...     'a': None,
...     'b': 2,
...     'c': {
...         'd': 'herm',
...         'e': None,
...         'falsey_dict': {},
...         'falsey_list': [],
...         'falsey_string': '',
...         'is_false': False,
...     },
...     }
...
>>> d = JsonObj(d)
>>> print(d)
JsonObj(**{
    'a': None,
    'b': 2,
    'c': {'d': 'herm',
          'e': None,
          'falsey_dict': {},
          'falsey_list': [],
          'falsey_string': '',
          'is_false': False},
    'falsey_dict': {},
    'falsey_list': [],
    'falsey_string': '',
    'is_false': False
})
>>> print(d.filter_none())
JsonObj(**{
    'b': 2,
    'c': {'d': 'herm',
          'e': None,
          'falsey_dict': {},
          'falsey_list': [],
          'falsey_string': '',
          'is_false': False},
    'falsey_dict': {},
    'falsey_list': [],
    'falsey_string': '',
    'is_false': False
})
>>> from pprint import pprint
>>> print(d.filter_none(recursive=True))
JsonObj(**{
    'b': 2,
    'c': {'d': 'herm',
          'falsey_dict': {},
          'falsey_list': [],
          'falsey_string': '',
          'is_false': False},
    'falsey_dict': {},
    'falsey_list': [],
    'falsey_string': '',
    'is_false': False
})
Source code in libs/jsonbourne/jsonbourne/core.py
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
def filter_none(self, recursive: bool = False) -> JsonObj[_VT]:
    """Filter key-values where the value is `None` but not false-y

    Args:
        recursive (bool): Recursively filter out None values

    Returns:
        JsonObj that has been filtered of None values

    Examples:
        >>> d = {
        ...     'falsey_dict': {},
        ...     'falsey_list': [],
        ...     'falsey_string': '',
        ...     'is_false': False,
        ...     'a': None,
        ...     'b': 2,
        ...     'c': {
        ...         'd': 'herm',
        ...         'e': None,
        ...         'falsey_dict': {},
        ...         'falsey_list': [],
        ...         'falsey_string': '',
        ...         'is_false': False,
        ...     },
        ...     }
        ...
        >>> d = JsonObj(d)
        >>> print(d)
        JsonObj(**{
            'a': None,
            'b': 2,
            'c': {'d': 'herm',
                  'e': None,
                  'falsey_dict': {},
                  'falsey_list': [],
                  'falsey_string': '',
                  'is_false': False},
            'falsey_dict': {},
            'falsey_list': [],
            'falsey_string': '',
            'is_false': False
        })
        >>> print(d.filter_none())
        JsonObj(**{
            'b': 2,
            'c': {'d': 'herm',
                  'e': None,
                  'falsey_dict': {},
                  'falsey_list': [],
                  'falsey_string': '',
                  'is_false': False},
            'falsey_dict': {},
            'falsey_list': [],
            'falsey_string': '',
            'is_false': False
        })
        >>> from pprint import pprint
        >>> print(d.filter_none(recursive=True))
        JsonObj(**{
            'b': 2,
            'c': {'d': 'herm',
                  'falsey_dict': {},
                  'falsey_list': [],
                  'falsey_string': '',
                  'is_false': False},
            'falsey_dict': {},
            'falsey_list': [],
            'falsey_string': '',
            'is_false': False
        })

    """
    if recursive:
        return JsonObj(
            cast(
                Dict[str, _VT],
                {
                    k: (
                        v
                        if not isinstance(v, (dict, JsonObj))
                        else JsonObj(v).filter_none(recursive=True)
                    )
                    for k, v in self.items()
                    if v is not None  # type: ignore[redundant-expr]
                },
            )
        )
    return JsonObj({k: v for k, v in self.items() if v is not None})  # type: ignore[redundant-expr]
jsonbourne.pydantic.JsonBaseModel.from_dict(data: Dict[_KT, _VT]) -> JsonObj[_VT] classmethod ⚓︎

Return a JsonObj object from a dictionary of data

Source code in libs/jsonbourne/jsonbourne/core.py
898
899
900
901
@classmethod
def from_dict(cls: Type[JsonObj[_VT]], data: Dict[_KT, _VT]) -> JsonObj[_VT]:
    """Return a JsonObj object from a dictionary of data"""
    return cls(**data)
jsonbourne.pydantic.JsonBaseModel.from_dict_filtered(dictionary: Dict[str, Any]) -> JsonBaseModelT classmethod ⚓︎

Create class from dict filtering keys not in (sub)class' fields

Source code in libs/jsonbourne/jsonbourne/pydantic.py
278
279
280
281
282
283
284
@classmethod
def from_dict_filtered(
    cls: Type[JsonBaseModelT], dictionary: Dict[str, Any]
) -> JsonBaseModelT:
    """Create class from dict filtering keys not in (sub)class' fields"""
    attr_names: Set[str] = set(cls._cls_field_names())
    return cls(**{k: v for k, v in dictionary.items() if k in attr_names})
jsonbourne.pydantic.JsonBaseModel.from_json(json_string: Union[bytes, str]) -> JsonObj[_VT] classmethod ⚓︎

Return a JsonObj object from a json string

Parameters:

Name Type Description Default
json_string str

JSON string to convert to a JsonObj

required

Returns:

Name Type Description
JsonObjT JsonObj[_VT]

JsonObj object for the given JSON string

Source code in libs/jsonbourne/jsonbourne/core.py
903
904
905
906
907
908
909
910
911
912
913
914
915
916
@classmethod
def from_json(
    cls: Type[JsonObj[_VT]], json_string: Union[bytes, str]
) -> JsonObj[_VT]:
    """Return a JsonObj object from a json string

    Args:
        json_string (str): JSON string to convert to a JsonObj

    Returns:
        JsonObjT: JsonObj object for the given JSON string

    """
    return cls._from_json(json_string)
jsonbourne.pydantic.JsonBaseModel.has_required_fields() -> bool classmethod ⚓︎

Return True/False if the (sub)class has any fields that are required

Returns:

Name Type Description
bool bool

True if any fields for a (sub)class are required

Source code in libs/jsonbourne/jsonbourne/pydantic.py
286
287
288
289
290
291
292
293
294
@classmethod
def has_required_fields(cls) -> bool:
    """Return True/False if the (sub)class has any fields that are required

    Returns:
        bool: True if any fields for a (sub)class are required

    """
    return any(val.is_required() for val in cls.model_fields.values())
jsonbourne.pydantic.JsonBaseModel.is_default() -> bool ⚓︎

Check if the object is equal to the default value for its fields

Returns:

Type Description
bool

True if object is equal to the default value for all fields; False otherwise

Examples:

>>> class Thing(JsonBaseModel):
...    a: int = 1
...    b: str = 'b'
...
>>> t = Thing()
>>> t.is_default()
True
>>> t = Thing(a=2)
>>> t.is_default()
False
Source code in libs/jsonbourne/jsonbourne/pydantic.py
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
def is_default(self) -> bool:
    """Check if the object is equal to the default value for its fields

    Returns:
        True if object is equal to the default value for all fields; False otherwise

    Examples:
        >>> class Thing(JsonBaseModel):
        ...    a: int = 1
        ...    b: str = 'b'
        ...
        >>> t = Thing()
        >>> t.is_default()
        True
        >>> t = Thing(a=2)
        >>> t.is_default()
        False

    """
    if self.has_required_fields():
        return False
    return all(
        mfield.default == self[fname] for fname, mfield in self.model_fields.items()
    )
jsonbourne.pydantic.JsonBaseModel.items() -> ItemsView[_KT, _VT] ⚓︎

Return an items view of the JsonObj object

Source code in libs/jsonbourne/jsonbourne/core.py
430
431
432
def items(self) -> ItemsView[_KT, _VT]:
    """Return an items view of the JsonObj object"""
    return self._data.items()
jsonbourne.pydantic.JsonBaseModel.json(*args: Any, **kwargs: Any) -> str ⚓︎

Alias for model_dumps

Source code in libs/jsonbourne/jsonbourne/pydantic.py
122
123
124
def json(self, *args: Any, **kwargs: Any) -> str:
    """Alias for `model_dumps`"""
    return self.model_dump_json(*args, **kwargs)
jsonbourne.pydantic.JsonBaseModel.keys() -> KeysView[_KT] ⚓︎

Return the keys view of the JsonObj object

Source code in libs/jsonbourne/jsonbourne/core.py
438
439
440
def keys(self) -> KeysView[_KT]:
    """Return the keys view of the JsonObj object"""
    return self._data.keys()
jsonbourne.pydantic.JsonBaseModel.recurse() -> None ⚓︎

Recursively convert all sub dictionaries to JsonObj objects

Source code in libs/jsonbourne/jsonbourne/core.py
256
257
258
def recurse(self) -> None:
    """Recursively convert all sub dictionaries to JsonObj objects"""
    self._data.update({k: jsonify(v) for k, v in self._data.items()})
jsonbourne.pydantic.JsonBaseModel.stringify(fmt: bool = False, pretty: bool = False, sort_keys: bool = False, append_newline: bool = False, default: Optional[Callable[[Any], Any]] = None, **kwargs: Any) -> str ⚓︎

Return JSON string of the JsonObj object (and children)

    Args:
        fmt (bool): If True, return a JSON string with newlines and indentation
        pretty (bool): If True, return a JSON string with newlines and indentation
        sort_keys (bool): Sort dictionary keys if True
        append_newline (bool): Append a newline '

' to JSON string if True default: default function hook for JSON serialization **kwargs (Any): additional kwargs to be passed down to jsonlib.dumps

    Returns:
        str: JSON string of the JsonObj object
Source code in libs/jsonbourne/jsonbourne/core.py
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
def stringify(
    self,
    fmt: bool = False,
    pretty: bool = False,
    sort_keys: bool = False,
    append_newline: bool = False,
    default: Optional[Callable[[Any], Any]] = None,
    **kwargs: Any,
) -> str:
    """Return JSON string of the JsonObj object (and children)

    Args:
        fmt (bool): If True, return a JSON string with newlines and indentation
        pretty (bool): If True, return a JSON string with newlines and indentation
        sort_keys (bool): Sort dictionary keys if True
        append_newline (bool): Append a newline '\n' to JSON string if True
        default: default function hook for JSON serialization
        **kwargs (Any): additional kwargs to be passed down to jsonlib.dumps

    Returns:
        str: JSON string of the JsonObj object

    """
    return self._to_json(
        fmt=fmt,
        pretty=pretty,
        sort_keys=sort_keys,
        append_newline=append_newline,
        default=default,
        **kwargs,
    )
jsonbourne.pydantic.JsonBaseModel.to_dict() -> Dict[str, Any] ⚓︎

Eject and return object as plain jane dictionary

Source code in libs/jsonbourne/jsonbourne/pydantic.py
255
256
257
def to_dict(self) -> Dict[str, Any]:
    """Eject and return object as plain jane dictionary"""
    return self.eject()
jsonbourne.pydantic.JsonBaseModel.to_dict_filter_defaults() -> Dict[str, Any] ⚓︎

Eject object and filter key-values equal to (sub)class' default

Examples:

>>> class Thing(JsonBaseModel):
...     a: int = 1
...     b: str = "herm"
...
>>> t = Thing()
>>> t
Thing(a=1, b='herm')
>>> t.to_dict_filter_defaults()
{}
>>> t.to_json_obj_filter_defaults()
JsonObj(**{})
>>> t = Thing(a=123)
>>> t
Thing(a=123, b='herm')
>>> t.to_dict_filter_defaults()
{'a': 123}
>>> t.to_json_obj_filter_defaults()
JsonObj(**{'a': 123})
Source code in libs/jsonbourne/jsonbourne/pydantic.py
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
def to_dict_filter_defaults(self) -> Dict[str, Any]:
    """Eject object and filter key-values equal to (sub)class' default

    Examples:
        >>> class Thing(JsonBaseModel):
        ...     a: int = 1
        ...     b: str = "herm"
        ...
        >>> t = Thing()
        >>> t
        Thing(a=1, b='herm')
        >>> t.to_dict_filter_defaults()
        {}
        >>> t.to_json_obj_filter_defaults()
        JsonObj(**{})
        >>> t = Thing(a=123)
        >>> t
        Thing(a=123, b='herm')
        >>> t.to_dict_filter_defaults()
        {'a': 123}
        >>> t.to_json_obj_filter_defaults()
        JsonObj(**{'a': 123})

    """
    defaults = self.defaults_dict()
    return {
        k: v
        for k, v in self.model_dump().items()
        if k not in defaults or v != defaults[k]
    }
jsonbourne.pydantic.JsonBaseModel.to_dict_filter_none() -> Dict[str, Any] ⚓︎

Eject object and filter key-values equal to (sub)class' default

Examples:

>>> from typing import Optional
>>> class Thing(JsonBaseModel):
...     a: int = 1
...     b: str = "herm"
...     c: Optional[str] = None
...
>>> t = Thing()
>>> t
Thing(a=1, b='herm', c=None)
>>> t.to_dict_filter_none()
{'a': 1, 'b': 'herm'}
>>> t.to_json_obj_filter_none()
JsonObj(**{'a': 1, 'b': 'herm'})
Source code in libs/jsonbourne/jsonbourne/pydantic.py
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
def to_dict_filter_none(self) -> Dict[str, Any]:
    """Eject object and filter key-values equal to (sub)class' default

    Examples:
        >>> from typing import Optional
        >>> class Thing(JsonBaseModel):
        ...     a: int = 1
        ...     b: str = "herm"
        ...     c: Optional[str] = None
        ...
        >>> t = Thing()
        >>> t
        Thing(a=1, b='herm', c=None)
        >>> t.to_dict_filter_none()
        {'a': 1, 'b': 'herm'}
        >>> t.to_json_obj_filter_none()
        JsonObj(**{'a': 1, 'b': 'herm'})

    """
    return {k: v for k, v in self.model_dump().items() if v is not None}
jsonbourne.pydantic.JsonBaseModel.to_json(fmt: bool = False, pretty: bool = False, sort_keys: bool = False, append_newline: bool = False, default: Optional[Callable[[Any], Any]] = None, **kwargs: Any) -> str ⚓︎

Return JSON string of the JsonObj object (and children)

    Args:
        fmt (bool): If True, return a JSON string with newlines and indentation
        pretty (bool): If True, return a JSON string with newlines and indentation
        sort_keys (bool): Sort dictionary keys if True
        append_newline (bool): Append a newline '

' to JSON string if True default: default function hook for JSON serialization **kwargs (Any): additional kwargs to be passed down to jsonlib.dumps

    Returns:
        str: JSON string of the JsonObj object
Source code in libs/jsonbourne/jsonbourne/core.py
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
def to_json(
    self,
    fmt: bool = False,
    pretty: bool = False,
    sort_keys: bool = False,
    append_newline: bool = False,
    default: Optional[Callable[[Any], Any]] = None,
    **kwargs: Any,
) -> str:
    """Return JSON string of the JsonObj object (and children)

    Args:
        fmt (bool): If True, return a JSON string with newlines and indentation
        pretty (bool): If True, return a JSON string with newlines and indentation
        sort_keys (bool): Sort dictionary keys if True
        append_newline (bool): Append a newline '\n' to JSON string if True
        default: default function hook for JSON serialization
        **kwargs (Any): additional kwargs to be passed down to jsonlib.dumps

    Returns:
        str: JSON string of the JsonObj object

    """
    return self._to_json(
        fmt=fmt,
        pretty=pretty,
        sort_keys=sort_keys,
        append_newline=append_newline,
        default=default,
        **kwargs,
    )
jsonbourne.pydantic.JsonBaseModel.to_json_dict() -> JsonObj[Any] ⚓︎

Eject object and sub-objects to jsonbourne.JsonObj

Examples:

>>> d = JsonObj(**{'uno': 'ONE', 'tres': 3, 'dos': 2})
>>> d
JsonObj(**{'uno': 'ONE', 'tres': 3, 'dos': 2})
>>> plain_ol_dict = d.eject()
>>> plain_ol_dict
{'uno': 'ONE', 'tres': 3, 'dos': 2}
>>> type(plain_ol_dict)
<class 'dict'>
Source code in libs/jsonbourne/jsonbourne/pydantic.py
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
def to_json_dict(self) -> JsonObj[Any]:
    """Eject object and sub-objects to `jsonbourne.JsonObj`

    Examples:
        >>> d = JsonObj(**{'uno': 'ONE', 'tres': 3, 'dos': 2})
        >>> d
        JsonObj(**{'uno': 'ONE', 'tres': 3, 'dos': 2})
        >>> plain_ol_dict = d.eject()
        >>> plain_ol_dict
        {'uno': 'ONE', 'tres': 3, 'dos': 2}
        >>> type(plain_ol_dict)
        <class 'dict'>

    """
    return self.to_json_obj()
jsonbourne.pydantic.JsonBaseModel.to_json_obj() -> JsonObj[Any] ⚓︎

Eject object and sub-objects to jsonbourne.JsonObj

Examples:

>>> d = JsonObj(**{'uno': 'ONE', 'tres': 3, 'dos': 2})
>>> d
JsonObj(**{'uno': 'ONE', 'tres': 3, 'dos': 2})
>>> plain_ol_dict = d.eject()
>>> plain_ol_dict
{'uno': 'ONE', 'tres': 3, 'dos': 2}
>>> type(plain_ol_dict)
<class 'dict'>
Source code in libs/jsonbourne/jsonbourne/pydantic.py
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
def to_json_obj(self) -> JsonObj[Any]:
    """Eject object and sub-objects to `jsonbourne.JsonObj`

    Examples:
        >>> d = JsonObj(**{'uno': 'ONE', 'tres': 3, 'dos': 2})
        >>> d
        JsonObj(**{'uno': 'ONE', 'tres': 3, 'dos': 2})
        >>> plain_ol_dict = d.eject()
        >>> plain_ol_dict
        {'uno': 'ONE', 'tres': 3, 'dos': 2}
        >>> type(plain_ol_dict)
        <class 'dict'>

    """
    return JsonObj(
        {
            k: v if not isinstance(v, JsonBaseModel) else v.to_json_dict()
            for k, v in self.__dict__.items()
        }
    )
jsonbourne.pydantic.JsonBaseModel.to_json_obj_filter_defaults() -> JsonObj[Any] ⚓︎

Eject to JsonObj and filter key-values equal to (sub)class' default

Source code in libs/jsonbourne/jsonbourne/pydantic.py
210
211
212
def to_json_obj_filter_defaults(self) -> JsonObj[Any]:
    """Eject to JsonObj and filter key-values equal to (sub)class' default"""
    return JsonObj(self.to_dict_filter_defaults())
jsonbourne.pydantic.JsonBaseModel.to_json_obj_filter_none() -> JsonObj[Any] ⚓︎

Eject to JsonObj and filter key-values where the value is None

Source code in libs/jsonbourne/jsonbourne/pydantic.py
214
215
216
def to_json_obj_filter_none(self) -> JsonObj[Any]:
    """Eject to JsonObj and filter key-values where the value is None"""
    return JsonObj(self.to_dict_filter_none())
jsonbourne.pydantic.JsonBaseModel.validate_type(val: Any) -> JsonObj[_VT] classmethod ⚓︎

Validate and convert a value to a JsonObj object

Source code in libs/jsonbourne/jsonbourne/core.py
1064
1065
1066
1067
@classmethod
def validate_type(cls: Type[JsonObj[_VT]], val: Any) -> JsonObj[_VT]:
    """Validate and convert a value to a JsonObj object"""
    return cls(val)

jsonbourne.trydantic ⚓︎

trydantic = try + pydantic


jsonbourne.pydantic ⚓︎

JSONBourne + Pydantic

Classes⚓︎

jsonbourne.pydantic.JsonBaseConfig ⚓︎

Pydantic v1 model config class for JsonBaseModel; can be overridden

jsonbourne.pydantic.JsonBaseModel(*args: Any, **kwargs: _VT) ⚓︎

Bases: BaseModel, JsonObj, MutableMapping

Hybrid pydantic.BaseModel and jsonbourne.JsonObj

Source code in libs/jsonbourne/jsonbourne/core.py
242
243
244
245
246
247
248
249
250
251
252
253
254
def __init__(
    self,
    *args: Any,
    **kwargs: _VT,
) -> None:
    """Use the object dict"""
    _data = dict(*args, **kwargs)
    super().__setattr__("_data", _data)
    if not all(isinstance(k, str) for k in self._data):
        d = {k: v for k, v in self._data.items() if not isinstance(k, str)}  # type: ignore[redundant-expr]
        raise ValueError(f"JsonObj keys MUST be strings! Bad key values: {str(d)}")
    self.recurse()
    self.__post_init__()
Attributes⚓︎
jsonbourne.pydantic.JsonBaseModel.__property_fields__: Set[str] property ⚓︎

Returns a set of property names for the class that have a setter

Functions⚓︎
jsonbourne.pydantic.JsonBaseModel.__contains__(key: _KT) -> bool ⚓︎

Check if a key or dot-key is contained within the JsonObj object

Parameters:

Name Type Description Default
key _KT

root level key or a dot-key

required

Returns:

Name Type Description
bool bool

True if the key/dot-key is in the JsonObj; False otherwise

Examples:

>>> d = {"uno": 1, "dos": 2, "tres": 3, "sub": {"a": 1, "b": 2, "c": [3, 4, 5, 6], "d": "a_string"}}
>>> d = JsonObj(d)
>>> d
JsonObj(**{'uno': 1, 'dos': 2, 'tres': 3, 'sub': {'a': 1, 'b': 2, 'c': [3, 4, 5, 6], 'd': 'a_string'}})
>>> 'uno' in d
True
>>> 'this_key_is_not_in_d' in d
False
>>> 'sub.a' in d
True
>>> 'sub.d.a' in d
False
Source code in libs/jsonbourne/jsonbourne/core.py
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
def __contains__(self, key: _KT) -> bool:  # type: ignore[override]
    """Check if a key or dot-key is contained within the JsonObj object

    Args:
        key (_KT): root level key or a dot-key

    Returns:
        bool: True if the key/dot-key is in the JsonObj; False otherwise

    Examples:
        >>> d = {"uno": 1, "dos": 2, "tres": 3, "sub": {"a": 1, "b": 2, "c": [3, 4, 5, 6], "d": "a_string"}}
        >>> d = JsonObj(d)
        >>> d
        JsonObj(**{'uno': 1, 'dos': 2, 'tres': 3, 'sub': {'a': 1, 'b': 2, 'c': [3, 4, 5, 6], 'd': 'a_string'}})
        >>> 'uno' in d
        True
        >>> 'this_key_is_not_in_d' in d
        False
        >>> 'sub.a' in d
        True
        >>> 'sub.d.a' in d
        False

    """
    if "." in key:
        first_key, _, rest = key.partition(".")
        val = self._data.get(first_key)
        return isinstance(val, MutableMapping) and val.__contains__(rest)
    return key in self._data
jsonbourne.pydantic.JsonBaseModel.__get_type_validator__(source_type: Any, handler: GetCoreSchemaHandler) -> Iterator[Callable[[Any], Any]] classmethod ⚓︎

Return the JsonObj validator functions

Source code in libs/jsonbourne/jsonbourne/core.py
1069
1070
1071
1072
1073
1074
@classmethod
def __get_type_validator__(
    cls, source_type: Any, handler: GetCoreSchemaHandler
) -> Iterator[Callable[[Any], Any]]:
    """Return the JsonObj validator functions"""
    yield cls.validate_type
jsonbourne.pydantic.JsonBaseModel.__getattr__(item: _KT) -> Any ⚓︎

Return an attr

Examples:

>>> d = {
...     'falsey_dict': {},
...     'falsey_list': [],
...     'falsey_string': '',
...     'is_false': False,
...     'a': None,
...     'b': 2,
...     'c': {
...         'd': 'herm',
...         'e': None,
...         'falsey_dict': {},
...         'falsey_list': [],
...         'falsey_string': '',
...         'is_false': False,
...     },
...     }
...
>>> d = JsonObj(d)
>>> d.__getattr__('b')
2
>>> d.b
2
Source code in libs/jsonbourne/jsonbourne/core.py
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
def __getattr__(self, item: _KT) -> Any:
    """Return an attr

    Examples:
        >>> d = {
        ...     'falsey_dict': {},
        ...     'falsey_list': [],
        ...     'falsey_string': '',
        ...     'is_false': False,
        ...     'a': None,
        ...     'b': 2,
        ...     'c': {
        ...         'd': 'herm',
        ...         'e': None,
        ...         'falsey_dict': {},
        ...         'falsey_list': [],
        ...         'falsey_string': '',
        ...         'is_false': False,
        ...     },
        ...     }
        ...
        >>> d = JsonObj(d)
        >>> d.__getattr__('b')
        2
        >>> d.b
        2

    """
    if item == "_data":
        try:
            return object.__getattribute__(self, "_data")
        except AttributeError:
            return self.__dict__
    if item in _JsonObjMutableMapping_attrs or item in self._cls_protected_attrs():
        return object.__getattribute__(self, item)
    try:
        return jsonify(self.__getitem__(str(item)))
    except KeyError:
        pass
    return object.__getattribute__(self, item)
jsonbourne.pydantic.JsonBaseModel.__post_init__() -> Any ⚓︎

Function place holder that is called after object initialization

Source code in libs/jsonbourne/jsonbourne/pydantic.py
98
99
def __post_init__(self) -> Any:
    """Function place holder that is called after object initialization"""
jsonbourne.pydantic.JsonBaseModel.__setitem__(key: _KT, value: _VT) -> None ⚓︎

Set JsonObj item with 'key' to 'value'

Parameters:

Name Type Description Default
key _KT

Key/item to set

required
value _VT

Value to set

required

Returns:

Type Description
None

None

Raises:

Type Description
ValueError

If given a key that is not a valid python keyword/identifier

Examples:

>>> d = JsonObj()
>>> d.a = 123
>>> d['b'] = 321
>>> d
JsonObj(**{'a': 123, 'b': 321})
>>> d[123] = 'a'
>>> d
JsonObj(**{'a': 123, 'b': 321, '123': 'a'})
>>> d['456'] = 'a'
>>> d
JsonObj(**{'a': 123, 'b': 321, '123': 'a', '456': 'a'})
Source code in libs/jsonbourne/jsonbourne/core.py
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
def __setitem__(self, key: _KT, value: _VT) -> None:
    """Set JsonObj item with 'key' to 'value'

    Args:
        key (_KT): Key/item to set
        value: Value to set

    Returns:
        None

    Raises:
        ValueError: If given a key that is not a valid python keyword/identifier

    Examples:
        >>> d = JsonObj()
        >>> d.a = 123
        >>> d['b'] = 321
        >>> d
        JsonObj(**{'a': 123, 'b': 321})
        >>> d[123] = 'a'
        >>> d
        JsonObj(**{'a': 123, 'b': 321, '123': 'a'})
        >>> d['456'] = 'a'
        >>> d
        JsonObj(**{'a': 123, 'b': 321, '123': 'a', '456': 'a'})

    """
    self.__setitem(key, value, identifier=False)
jsonbourne.pydantic.JsonBaseModel.asdict() -> Dict[_KT, Any] ⚓︎

Return the JsonObj object (and children) as a python dictionary

Source code in libs/jsonbourne/jsonbourne/core.py
894
895
896
def asdict(self) -> Dict[_KT, Any]:
    """Return the JsonObj object (and children) as a python dictionary"""
    return self.eject()
jsonbourne.pydantic.JsonBaseModel.defaults_dict() -> Dict[str, Any] classmethod ⚓︎

Return a dictionary of non-required keys -> default value(s)

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: Dictionary of non-required keys -> default value

Examples:

>>> class Thing(JsonBaseModel):
...     a: int = 1
...     b: str = "herm"
...
>>> t = Thing()
>>> t
Thing(a=1, b='herm')
>>> t.to_dict_filter_defaults()
{}
>>> t.to_json_obj_filter_defaults()
JsonObj(**{})
>>> t = Thing(a=123)
>>> t
Thing(a=123, b='herm')
>>> t.to_dict_filter_defaults()
{'a': 123}
>>> t.to_json_obj_filter_defaults()
JsonObj(**{'a': 123})
>>> t.defaults_dict()
{'a': 1, 'b': 'herm'}
Source code in libs/jsonbourne/jsonbourne/pydantic.py
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
@classmethod
def defaults_dict(cls) -> Dict[str, Any]:
    """Return a dictionary of non-required keys -> default value(s)

    Returns:
        Dict[str, Any]: Dictionary of non-required keys -> default value

    Examples:
        >>> class Thing(JsonBaseModel):
        ...     a: int = 1
        ...     b: str = "herm"
        ...
        >>> t = Thing()
        >>> t
        Thing(a=1, b='herm')
        >>> t.to_dict_filter_defaults()
        {}
        >>> t.to_json_obj_filter_defaults()
        JsonObj(**{})
        >>> t = Thing(a=123)
        >>> t
        Thing(a=123, b='herm')
        >>> t.to_dict_filter_defaults()
        {'a': 123}
        >>> t.to_json_obj_filter_defaults()
        JsonObj(**{'a': 123})
        >>> t.defaults_dict()
        {'a': 1, 'b': 'herm'}

    """
    return {
        k: v.default for k, v in cls.model_fields.items() if not v.is_required()
    }
jsonbourne.pydantic.JsonBaseModel.dict(*args: Any, **kwargs: Any) -> Dict[str, Any] ⚓︎

Alias for model_dump

Source code in libs/jsonbourne/jsonbourne/pydantic.py
118
119
120
def dict(self, *args: Any, **kwargs: Any) -> Dict[str, Any]:
    """Alias for `model_dump`"""
    return self.model_dump(*args, **kwargs)
jsonbourne.pydantic.JsonBaseModel.dot_items() -> Iterator[Tuple[Tuple[str, ...], _VT]] ⚓︎

Yield tuples of the form (dot-key, value)

OG-version

def dot_items(self) -> Iterator[Tuple[str, Any]]: return ((dk, self.dot_lookup(dk)) for dk in self.dot_keys())

Readable-version

for k, value in self.items(): value = jsonify(value) if isinstance(value, JsonObj) or hasattr(value, 'dot_items'): yield from ((f"{k}.{dk}", dv) for dk, dv in value.dot_items()) else: yield k, value

Source code in libs/jsonbourne/jsonbourne/core.py
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
def dot_items(self) -> Iterator[Tuple[Tuple[str, ...], _VT]]:
    """Yield tuples of the form (dot-key, value)

    OG-version:
        def dot_items(self) -> Iterator[Tuple[str, Any]]:
            return ((dk, self.dot_lookup(dk)) for dk in self.dot_keys())

    Readable-version:
        for k, value in self.items():
            value = jsonify(value)
            if isinstance(value, JsonObj) or hasattr(value, 'dot_items'):
                yield from ((f"{k}.{dk}", dv) for dk, dv in value.dot_items())
            else:
                yield k, value
    """

    return chain.from_iterable(
        (
            (
                (
                    *(
                        (
                            (
                                str(k),
                                *dk,
                            ),
                            dv,
                        )
                        for dk, dv in as_json_obj(v).dot_items()
                    ),
                )
                if isinstance(v, (JsonObj, dict))
                else (((str(k),), v),)
            )
            for k, v in self.items()
        )
    )
jsonbourne.pydantic.JsonBaseModel.dot_items_list() -> List[Tuple[Tuple[str, ...], Any]] ⚓︎

Return list of tuples of the form (dot-key, value)

Source code in libs/jsonbourne/jsonbourne/core.py
763
764
765
def dot_items_list(self) -> List[Tuple[Tuple[str, ...], Any]]:
    """Return list of tuples of the form (dot-key, value)"""
    return list(self.dot_items())
jsonbourne.pydantic.JsonBaseModel.dot_keys() -> Iterable[Tuple[str, ...]] ⚓︎

Yield the JsonObj's dot-notation keys

Returns:

Type Description
Iterable[Tuple[str, ...]]

Iterable[str]: List of the dot-notation friendly keys

The Non-chain version (shown below) is very slightly slower than the itertools.chain version.

NON-CHAIN VERSION:

for k, value in self.items(): value = jsonify(value) if isinstance(value, JsonObj): yield from (f"{k}.{dk}" for dk in value.dot_keys()) else: yield k

Source code in libs/jsonbourne/jsonbourne/core.py
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
def dot_keys(self) -> Iterable[Tuple[str, ...]]:
    """Yield the JsonObj's dot-notation keys

    Returns:
        Iterable[str]: List of the dot-notation friendly keys


    The Non-chain version (shown below) is very slightly slower than the
    `itertools.chain` version.

    NON-CHAIN VERSION:

    for k, value in self.items():
        value = jsonify(value)
        if isinstance(value, JsonObj):
            yield from (f"{k}.{dk}" for dk in value.dot_keys())
        else:
            yield k

    """
    return chain(
        *(
            (
                ((str(k),),)
                if not isinstance(v, JsonObj)
                else (*((str(k), *dk) for dk in jsonify(v).dot_keys()),)
            )
            for k, v in self.items()
        )
    )
jsonbourne.pydantic.JsonBaseModel.dot_keys_list(sort_keys: bool = False) -> List[Tuple[str, ...]] ⚓︎

Return a list of the JsonObj's dot-notation friendly keys

Parameters:

Name Type Description Default
sort_keys bool

Flag to have the dot-keys be returned sorted

False

Returns:

Type Description
List[Tuple[str, ...]]

List[str]: List of the dot-notation friendly keys

Source code in libs/jsonbourne/jsonbourne/core.py
660
661
662
663
664
665
666
667
668
669
670
671
672
def dot_keys_list(self, sort_keys: bool = False) -> List[Tuple[str, ...]]:
    """Return a list of the JsonObj's dot-notation friendly keys

    Args:
        sort_keys (bool): Flag to have the dot-keys be returned sorted

    Returns:
        List[str]: List of the dot-notation friendly keys

    """
    if sort_keys:
        return sorted(self.dot_keys_list())
    return list(self.dot_keys())
jsonbourne.pydantic.JsonBaseModel.dot_keys_set() -> Set[Tuple[str, ...]] ⚓︎

Return a set of the JsonObj's dot-notation friendly keys

Returns:

Type Description
Set[Tuple[str, ...]]

Set[str]: List of the dot-notation friendly keys

Source code in libs/jsonbourne/jsonbourne/core.py
674
675
676
677
678
679
680
681
def dot_keys_set(self) -> Set[Tuple[str, ...]]:
    """Return a set of the JsonObj's dot-notation friendly keys

    Returns:
        Set[str]: List of the dot-notation friendly keys

    """
    return set(self.dot_keys())
jsonbourne.pydantic.JsonBaseModel.dot_lookup(key: Union[str, Tuple[str, ...], List[str]]) -> Any ⚓︎

Look up JsonObj keys using dot notation as a string

Parameters:

Name Type Description Default
key str

dot-notation key to look up ('key1.key2.third_key')

required

Returns:

Type Description
Any

The result of the dot-notation key look up

Raises:

Type Description
KeyError

Raised if the dot-key is not in in the object

ValueError

Raised if key is not a str/Tuple[str, ...]/List[str]

Source code in libs/jsonbourne/jsonbourne/core.py
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
def dot_lookup(self, key: Union[str, Tuple[str, ...], List[str]]) -> Any:
    """Look up JsonObj keys using dot notation as a string

    Args:
        key (str): dot-notation key to look up ('key1.key2.third_key')

    Returns:
        The result of the dot-notation key look up

    Raises:
        KeyError: Raised if the dot-key is not in in the object
        ValueError: Raised if key is not a str/Tuple[str, ...]/List[str]

    """
    if not isinstance(key, (str, list, tuple)):
        raise ValueError(
            "".join(
                (
                    "dot_key arg must be string or sequence of strings; ",
                    "strings will be split on '.'",
                )
            )
        )
    parts = key.split(".") if isinstance(key, str) else list(key)
    root_val: Any = self._data[parts[0]]
    cur_val = root_val
    for ix, part in enumerate(parts[1:], start=1):
        try:
            cur_val = cur_val[part]
        except TypeError as e:
            reached = ".".join(parts[:ix])
            err_msg = f"Invalid DotKey: {key} -- Lookup reached: {reached} => {str(cur_val)}"
            if isinstance(key, str):
                err_msg += "".join(
                    (
                        f"\nNOTE!!! lookup performed with string ('{key}') ",
                        "PREFER lookup using List[str] or Tuple[str, ...]",
                    )
                )
            raise KeyError(err_msg) from e
    return cur_val
jsonbourne.pydantic.JsonBaseModel.eject() -> Dict[_KT, _VT] ⚓︎

Eject to python-builtin dictionary object

Examples:

>>> d = JsonObj(**{'uno': 'ONE', 'tres': 3, 'dos': 2})
>>> d
JsonObj(**{'uno': 'ONE', 'tres': 3, 'dos': 2})
>>> plain_ol_dict = d.eject()
>>> plain_ol_dict
{'uno': 'ONE', 'tres': 3, 'dos': 2}
>>> type(plain_ol_dict)
<class 'dict'>
Source code in libs/jsonbourne/jsonbourne/core.py
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
def eject(self) -> Dict[_KT, _VT]:
    """Eject to python-builtin dictionary object

    Examples:
        >>> d = JsonObj(**{'uno': 'ONE', 'tres': 3, 'dos': 2})
        >>> d
        JsonObj(**{'uno': 'ONE', 'tres': 3, 'dos': 2})
        >>> plain_ol_dict = d.eject()
        >>> plain_ol_dict
        {'uno': 'ONE', 'tres': 3, 'dos': 2}
        >>> type(plain_ol_dict)
        <class 'dict'>

    """
    try:
        return {k: unjsonify(v) for k, v in self._data.items()}
    except RecursionError as re:
        raise ValueError(
            "JSON.stringify recursion err; cycle/circular-refs detected"
        ) from re
jsonbourne.pydantic.JsonBaseModel.entries() -> ItemsView[_KT, _VT] ⚓︎

Alias for items

Source code in libs/jsonbourne/jsonbourne/core.py
434
435
436
def entries(self) -> ItemsView[_KT, _VT]:
    """Alias for items"""
    return self.items()
jsonbourne.pydantic.JsonBaseModel.filter_false(recursive: bool = False) -> JsonObj[_VT] ⚓︎

Filter key-values where the value is false-y

Parameters:

Name Type Description Default
recursive bool

Recurse into sub JsonObjs and dictionaries

False

Returns:

Type Description
JsonObj[_VT]

JsonObj that has been filtered

Examples:

>>> d = {
...     'falsey_dict': {},
...     'falsey_list': [],
...     'falsey_string': '',
...     'is_false': False,
...     'a': None,
...     'b': 2,
...     'c': {
...         'd': 'herm',
...         'e': None,
...         'falsey_dict': {},
...         'falsey_list': [],
...         'falsey_string': '',
...         'is_false': False,
...     },
...     }
...
>>> d = JsonObj(d)
>>> print(d)
JsonObj(**{
    'a': None,
    'b': 2,
    'c': {'d': 'herm',
          'e': None,
          'falsey_dict': {},
          'falsey_list': [],
          'falsey_string': '',
          'is_false': False},
    'falsey_dict': {},
    'falsey_list': [],
    'falsey_string': '',
    'is_false': False
})
>>> print(d.filter_false())
JsonObj(**{
    'b': 2,
    'c': {'d': 'herm',
          'e': None,
          'falsey_dict': {},
          'falsey_list': [],
          'falsey_string': '',
          'is_false': False}
})
>>> print(d.filter_false(recursive=True))
JsonObj(**{
    'b': 2, 'c': {'d': 'herm'}
})
Source code in libs/jsonbourne/jsonbourne/core.py
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
def filter_false(self, recursive: bool = False) -> JsonObj[_VT]:
    """Filter key-values where the value is false-y

    Args:
        recursive (bool): Recurse into sub JsonObjs and dictionaries

    Returns:
        JsonObj that has been filtered

    Examples:
        >>> d = {
        ...     'falsey_dict': {},
        ...     'falsey_list': [],
        ...     'falsey_string': '',
        ...     'is_false': False,
        ...     'a': None,
        ...     'b': 2,
        ...     'c': {
        ...         'd': 'herm',
        ...         'e': None,
        ...         'falsey_dict': {},
        ...         'falsey_list': [],
        ...         'falsey_string': '',
        ...         'is_false': False,
        ...     },
        ...     }
        ...
        >>> d = JsonObj(d)
        >>> print(d)
        JsonObj(**{
            'a': None,
            'b': 2,
            'c': {'d': 'herm',
                  'e': None,
                  'falsey_dict': {},
                  'falsey_list': [],
                  'falsey_string': '',
                  'is_false': False},
            'falsey_dict': {},
            'falsey_list': [],
            'falsey_string': '',
            'is_false': False
        })
        >>> print(d.filter_false())
        JsonObj(**{
            'b': 2,
            'c': {'d': 'herm',
                  'e': None,
                  'falsey_dict': {},
                  'falsey_list': [],
                  'falsey_string': '',
                  'is_false': False}
        })
        >>> print(d.filter_false(recursive=True))
        JsonObj(**{
            'b': 2, 'c': {'d': 'herm'}
        })

    """
    if recursive:
        return JsonObj(
            cast(
                Dict[str, _VT],
                {
                    k: (
                        v
                        if not isinstance(v, (dict, JsonObj))
                        else JsonObj(v).filter_false(recursive=True)
                    )
                    for k, v in self.items()
                    if v
                },
            )
        )
    return JsonObj({k: v for k, v in self.items() if v})
jsonbourne.pydantic.JsonBaseModel.filter_none(recursive: bool = False) -> JsonObj[_VT] ⚓︎

Filter key-values where the value is None but not false-y

Parameters:

Name Type Description Default
recursive bool

Recursively filter out None values

False

Returns:

Type Description
JsonObj[_VT]

JsonObj that has been filtered of None values

Examples:

>>> d = {
...     'falsey_dict': {},
...     'falsey_list': [],
...     'falsey_string': '',
...     'is_false': False,
...     'a': None,
...     'b': 2,
...     'c': {
...         'd': 'herm',
...         'e': None,
...         'falsey_dict': {},
...         'falsey_list': [],
...         'falsey_string': '',
...         'is_false': False,
...     },
...     }
...
>>> d = JsonObj(d)
>>> print(d)
JsonObj(**{
    'a': None,
    'b': 2,
    'c': {'d': 'herm',
          'e': None,
          'falsey_dict': {},
          'falsey_list': [],
          'falsey_string': '',
          'is_false': False},
    'falsey_dict': {},
    'falsey_list': [],
    'falsey_string': '',
    'is_false': False
})
>>> print(d.filter_none())
JsonObj(**{
    'b': 2,
    'c': {'d': 'herm',
          'e': None,
          'falsey_dict': {},
          'falsey_list': [],
          'falsey_string': '',
          'is_false': False},
    'falsey_dict': {},
    'falsey_list': [],
    'falsey_string': '',
    'is_false': False
})
>>> from pprint import pprint
>>> print(d.filter_none(recursive=True))
JsonObj(**{
    'b': 2,
    'c': {'d': 'herm',
          'falsey_dict': {},
          'falsey_list': [],
          'falsey_string': '',
          'is_false': False},
    'falsey_dict': {},
    'falsey_list': [],
    'falsey_string': '',
    'is_false': False
})
Source code in libs/jsonbourne/jsonbourne/core.py
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
def filter_none(self, recursive: bool = False) -> JsonObj[_VT]:
    """Filter key-values where the value is `None` but not false-y

    Args:
        recursive (bool): Recursively filter out None values

    Returns:
        JsonObj that has been filtered of None values

    Examples:
        >>> d = {
        ...     'falsey_dict': {},
        ...     'falsey_list': [],
        ...     'falsey_string': '',
        ...     'is_false': False,
        ...     'a': None,
        ...     'b': 2,
        ...     'c': {
        ...         'd': 'herm',
        ...         'e': None,
        ...         'falsey_dict': {},
        ...         'falsey_list': [],
        ...         'falsey_string': '',
        ...         'is_false': False,
        ...     },
        ...     }
        ...
        >>> d = JsonObj(d)
        >>> print(d)
        JsonObj(**{
            'a': None,
            'b': 2,
            'c': {'d': 'herm',
                  'e': None,
                  'falsey_dict': {},
                  'falsey_list': [],
                  'falsey_string': '',
                  'is_false': False},
            'falsey_dict': {},
            'falsey_list': [],
            'falsey_string': '',
            'is_false': False
        })
        >>> print(d.filter_none())
        JsonObj(**{
            'b': 2,
            'c': {'d': 'herm',
                  'e': None,
                  'falsey_dict': {},
                  'falsey_list': [],
                  'falsey_string': '',
                  'is_false': False},
            'falsey_dict': {},
            'falsey_list': [],
            'falsey_string': '',
            'is_false': False
        })
        >>> from pprint import pprint
        >>> print(d.filter_none(recursive=True))
        JsonObj(**{
            'b': 2,
            'c': {'d': 'herm',
                  'falsey_dict': {},
                  'falsey_list': [],
                  'falsey_string': '',
                  'is_false': False},
            'falsey_dict': {},
            'falsey_list': [],
            'falsey_string': '',
            'is_false': False
        })

    """
    if recursive:
        return JsonObj(
            cast(
                Dict[str, _VT],
                {
                    k: (
                        v
                        if not isinstance(v, (dict, JsonObj))
                        else JsonObj(v).filter_none(recursive=True)
                    )
                    for k, v in self.items()
                    if v is not None  # type: ignore[redundant-expr]
                },
            )
        )
    return JsonObj({k: v for k, v in self.items() if v is not None})  # type: ignore[redundant-expr]
jsonbourne.pydantic.JsonBaseModel.from_dict(data: Dict[_KT, _VT]) -> JsonObj[_VT] classmethod ⚓︎

Return a JsonObj object from a dictionary of data

Source code in libs/jsonbourne/jsonbourne/core.py
898
899
900
901
@classmethod
def from_dict(cls: Type[JsonObj[_VT]], data: Dict[_KT, _VT]) -> JsonObj[_VT]:
    """Return a JsonObj object from a dictionary of data"""
    return cls(**data)
jsonbourne.pydantic.JsonBaseModel.from_dict_filtered(dictionary: Dict[str, Any]) -> JsonBaseModelT classmethod ⚓︎

Create class from dict filtering keys not in (sub)class' fields

Source code in libs/jsonbourne/jsonbourne/pydantic.py
278
279
280
281
282
283
284
@classmethod
def from_dict_filtered(
    cls: Type[JsonBaseModelT], dictionary: Dict[str, Any]
) -> JsonBaseModelT:
    """Create class from dict filtering keys not in (sub)class' fields"""
    attr_names: Set[str] = set(cls._cls_field_names())
    return cls(**{k: v for k, v in dictionary.items() if k in attr_names})
jsonbourne.pydantic.JsonBaseModel.from_json(json_string: Union[bytes, str]) -> JsonObj[_VT] classmethod ⚓︎

Return a JsonObj object from a json string

Parameters:

Name Type Description Default
json_string str

JSON string to convert to a JsonObj

required

Returns:

Name Type Description
JsonObjT JsonObj[_VT]

JsonObj object for the given JSON string

Source code in libs/jsonbourne/jsonbourne/core.py
903
904
905
906
907
908
909
910
911
912
913
914
915
916
@classmethod
def from_json(
    cls: Type[JsonObj[_VT]], json_string: Union[bytes, str]
) -> JsonObj[_VT]:
    """Return a JsonObj object from a json string

    Args:
        json_string (str): JSON string to convert to a JsonObj

    Returns:
        JsonObjT: JsonObj object for the given JSON string

    """
    return cls._from_json(json_string)
jsonbourne.pydantic.JsonBaseModel.has_required_fields() -> bool classmethod ⚓︎

Return True/False if the (sub)class has any fields that are required

Returns:

Name Type Description
bool bool

True if any fields for a (sub)class are required

Source code in libs/jsonbourne/jsonbourne/pydantic.py
286
287
288
289
290
291
292
293
294
@classmethod
def has_required_fields(cls) -> bool:
    """Return True/False if the (sub)class has any fields that are required

    Returns:
        bool: True if any fields for a (sub)class are required

    """
    return any(val.is_required() for val in cls.model_fields.values())
jsonbourne.pydantic.JsonBaseModel.is_default() -> bool ⚓︎

Check if the object is equal to the default value for its fields

Returns:

Type Description
bool

True if object is equal to the default value for all fields; False otherwise

Examples:

>>> class Thing(JsonBaseModel):
...    a: int = 1
...    b: str = 'b'
...
>>> t = Thing()
>>> t.is_default()
True
>>> t = Thing(a=2)
>>> t.is_default()
False
Source code in libs/jsonbourne/jsonbourne/pydantic.py
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
def is_default(self) -> bool:
    """Check if the object is equal to the default value for its fields

    Returns:
        True if object is equal to the default value for all fields; False otherwise

    Examples:
        >>> class Thing(JsonBaseModel):
        ...    a: int = 1
        ...    b: str = 'b'
        ...
        >>> t = Thing()
        >>> t.is_default()
        True
        >>> t = Thing(a=2)
        >>> t.is_default()
        False

    """
    if self.has_required_fields():
        return False
    return all(
        mfield.default == self[fname] for fname, mfield in self.model_fields.items()
    )
jsonbourne.pydantic.JsonBaseModel.items() -> ItemsView[_KT, _VT] ⚓︎

Return an items view of the JsonObj object

Source code in libs/jsonbourne/jsonbourne/core.py
430
431
432
def items(self) -> ItemsView[_KT, _VT]:
    """Return an items view of the JsonObj object"""
    return self._data.items()
jsonbourne.pydantic.JsonBaseModel.json(*args: Any, **kwargs: Any) -> str ⚓︎

Alias for model_dumps

Source code in libs/jsonbourne/jsonbourne/pydantic.py
122
123
124
def json(self, *args: Any, **kwargs: Any) -> str:
    """Alias for `model_dumps`"""
    return self.model_dump_json(*args, **kwargs)
jsonbourne.pydantic.JsonBaseModel.keys() -> KeysView[_KT] ⚓︎

Return the keys view of the JsonObj object

Source code in libs/jsonbourne/jsonbourne/core.py
438
439
440
def keys(self) -> KeysView[_KT]:
    """Return the keys view of the JsonObj object"""
    return self._data.keys()
jsonbourne.pydantic.JsonBaseModel.recurse() -> None ⚓︎

Recursively convert all sub dictionaries to JsonObj objects

Source code in libs/jsonbourne/jsonbourne/core.py
256
257
258
def recurse(self) -> None:
    """Recursively convert all sub dictionaries to JsonObj objects"""
    self._data.update({k: jsonify(v) for k, v in self._data.items()})
jsonbourne.pydantic.JsonBaseModel.stringify(fmt: bool = False, pretty: bool = False, sort_keys: bool = False, append_newline: bool = False, default: Optional[Callable[[Any], Any]] = None, **kwargs: Any) -> str ⚓︎

Return JSON string of the JsonObj object (and children)

    Args:
        fmt (bool): If True, return a JSON string with newlines and indentation
        pretty (bool): If True, return a JSON string with newlines and indentation
        sort_keys (bool): Sort dictionary keys if True
        append_newline (bool): Append a newline '

' to JSON string if True default: default function hook for JSON serialization **kwargs (Any): additional kwargs to be passed down to jsonlib.dumps

    Returns:
        str: JSON string of the JsonObj object
Source code in libs/jsonbourne/jsonbourne/core.py
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
def stringify(
    self,
    fmt: bool = False,
    pretty: bool = False,
    sort_keys: bool = False,
    append_newline: bool = False,
    default: Optional[Callable[[Any], Any]] = None,
    **kwargs: Any,
) -> str:
    """Return JSON string of the JsonObj object (and children)

    Args:
        fmt (bool): If True, return a JSON string with newlines and indentation
        pretty (bool): If True, return a JSON string with newlines and indentation
        sort_keys (bool): Sort dictionary keys if True
        append_newline (bool): Append a newline '\n' to JSON string if True
        default: default function hook for JSON serialization
        **kwargs (Any): additional kwargs to be passed down to jsonlib.dumps

    Returns:
        str: JSON string of the JsonObj object

    """
    return self._to_json(
        fmt=fmt,
        pretty=pretty,
        sort_keys=sort_keys,
        append_newline=append_newline,
        default=default,
        **kwargs,
    )
jsonbourne.pydantic.JsonBaseModel.to_dict() -> Dict[str, Any] ⚓︎

Eject and return object as plain jane dictionary

Source code in libs/jsonbourne/jsonbourne/pydantic.py
255
256
257
def to_dict(self) -> Dict[str, Any]:
    """Eject and return object as plain jane dictionary"""
    return self.eject()
jsonbourne.pydantic.JsonBaseModel.to_dict_filter_defaults() -> Dict[str, Any] ⚓︎

Eject object and filter key-values equal to (sub)class' default

Examples:

>>> class Thing(JsonBaseModel):
...     a: int = 1
...     b: str = "herm"
...
>>> t = Thing()
>>> t
Thing(a=1, b='herm')
>>> t.to_dict_filter_defaults()
{}
>>> t.to_json_obj_filter_defaults()
JsonObj(**{})
>>> t = Thing(a=123)
>>> t
Thing(a=123, b='herm')
>>> t.to_dict_filter_defaults()
{'a': 123}
>>> t.to_json_obj_filter_defaults()
JsonObj(**{'a': 123})
Source code in libs/jsonbourne/jsonbourne/pydantic.py
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
def to_dict_filter_defaults(self) -> Dict[str, Any]:
    """Eject object and filter key-values equal to (sub)class' default

    Examples:
        >>> class Thing(JsonBaseModel):
        ...     a: int = 1
        ...     b: str = "herm"
        ...
        >>> t = Thing()
        >>> t
        Thing(a=1, b='herm')
        >>> t.to_dict_filter_defaults()
        {}
        >>> t.to_json_obj_filter_defaults()
        JsonObj(**{})
        >>> t = Thing(a=123)
        >>> t
        Thing(a=123, b='herm')
        >>> t.to_dict_filter_defaults()
        {'a': 123}
        >>> t.to_json_obj_filter_defaults()
        JsonObj(**{'a': 123})

    """
    defaults = self.defaults_dict()
    return {
        k: v
        for k, v in self.model_dump().items()
        if k not in defaults or v != defaults[k]
    }
jsonbourne.pydantic.JsonBaseModel.to_dict_filter_none() -> Dict[str, Any] ⚓︎

Eject object and filter key-values equal to (sub)class' default

Examples:

>>> from typing import Optional
>>> class Thing(JsonBaseModel):
...     a: int = 1
...     b: str = "herm"
...     c: Optional[str] = None
...
>>> t = Thing()
>>> t
Thing(a=1, b='herm', c=None)
>>> t.to_dict_filter_none()
{'a': 1, 'b': 'herm'}
>>> t.to_json_obj_filter_none()
JsonObj(**{'a': 1, 'b': 'herm'})
Source code in libs/jsonbourne/jsonbourne/pydantic.py
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
def to_dict_filter_none(self) -> Dict[str, Any]:
    """Eject object and filter key-values equal to (sub)class' default

    Examples:
        >>> from typing import Optional
        >>> class Thing(JsonBaseModel):
        ...     a: int = 1
        ...     b: str = "herm"
        ...     c: Optional[str] = None
        ...
        >>> t = Thing()
        >>> t
        Thing(a=1, b='herm', c=None)
        >>> t.to_dict_filter_none()
        {'a': 1, 'b': 'herm'}
        >>> t.to_json_obj_filter_none()
        JsonObj(**{'a': 1, 'b': 'herm'})

    """
    return {k: v for k, v in self.model_dump().items() if v is not None}
jsonbourne.pydantic.JsonBaseModel.to_json(fmt: bool = False, pretty: bool = False, sort_keys: bool = False, append_newline: bool = False, default: Optional[Callable[[Any], Any]] = None, **kwargs: Any) -> str ⚓︎

Return JSON string of the JsonObj object (and children)

    Args:
        fmt (bool): If True, return a JSON string with newlines and indentation
        pretty (bool): If True, return a JSON string with newlines and indentation
        sort_keys (bool): Sort dictionary keys if True
        append_newline (bool): Append a newline '

' to JSON string if True default: default function hook for JSON serialization **kwargs (Any): additional kwargs to be passed down to jsonlib.dumps

    Returns:
        str: JSON string of the JsonObj object
Source code in libs/jsonbourne/jsonbourne/core.py
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
def to_json(
    self,
    fmt: bool = False,
    pretty: bool = False,
    sort_keys: bool = False,
    append_newline: bool = False,
    default: Optional[Callable[[Any], Any]] = None,
    **kwargs: Any,
) -> str:
    """Return JSON string of the JsonObj object (and children)

    Args:
        fmt (bool): If True, return a JSON string with newlines and indentation
        pretty (bool): If True, return a JSON string with newlines and indentation
        sort_keys (bool): Sort dictionary keys if True
        append_newline (bool): Append a newline '\n' to JSON string if True
        default: default function hook for JSON serialization
        **kwargs (Any): additional kwargs to be passed down to jsonlib.dumps

    Returns:
        str: JSON string of the JsonObj object

    """
    return self._to_json(
        fmt=fmt,
        pretty=pretty,
        sort_keys=sort_keys,
        append_newline=append_newline,
        default=default,
        **kwargs,
    )
jsonbourne.pydantic.JsonBaseModel.to_json_dict() -> JsonObj[Any] ⚓︎

Eject object and sub-objects to jsonbourne.JsonObj

Examples:

>>> d = JsonObj(**{'uno': 'ONE', 'tres': 3, 'dos': 2})
>>> d
JsonObj(**{'uno': 'ONE', 'tres': 3, 'dos': 2})
>>> plain_ol_dict = d.eject()
>>> plain_ol_dict
{'uno': 'ONE', 'tres': 3, 'dos': 2}
>>> type(plain_ol_dict)
<class 'dict'>
Source code in libs/jsonbourne/jsonbourne/pydantic.py
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
def to_json_dict(self) -> JsonObj[Any]:
    """Eject object and sub-objects to `jsonbourne.JsonObj`

    Examples:
        >>> d = JsonObj(**{'uno': 'ONE', 'tres': 3, 'dos': 2})
        >>> d
        JsonObj(**{'uno': 'ONE', 'tres': 3, 'dos': 2})
        >>> plain_ol_dict = d.eject()
        >>> plain_ol_dict
        {'uno': 'ONE', 'tres': 3, 'dos': 2}
        >>> type(plain_ol_dict)
        <class 'dict'>

    """
    return self.to_json_obj()
jsonbourne.pydantic.JsonBaseModel.to_json_obj() -> JsonObj[Any] ⚓︎

Eject object and sub-objects to jsonbourne.JsonObj

Examples:

>>> d = JsonObj(**{'uno': 'ONE', 'tres': 3, 'dos': 2})
>>> d
JsonObj(**{'uno': 'ONE', 'tres': 3, 'dos': 2})
>>> plain_ol_dict = d.eject()
>>> plain_ol_dict
{'uno': 'ONE', 'tres': 3, 'dos': 2}
>>> type(plain_ol_dict)
<class 'dict'>
Source code in libs/jsonbourne/jsonbourne/pydantic.py
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
def to_json_obj(self) -> JsonObj[Any]:
    """Eject object and sub-objects to `jsonbourne.JsonObj`

    Examples:
        >>> d = JsonObj(**{'uno': 'ONE', 'tres': 3, 'dos': 2})
        >>> d
        JsonObj(**{'uno': 'ONE', 'tres': 3, 'dos': 2})
        >>> plain_ol_dict = d.eject()
        >>> plain_ol_dict
        {'uno': 'ONE', 'tres': 3, 'dos': 2}
        >>> type(plain_ol_dict)
        <class 'dict'>

    """
    return JsonObj(
        {
            k: v if not isinstance(v, JsonBaseModel) else v.to_json_dict()
            for k, v in self.__dict__.items()
        }
    )
jsonbourne.pydantic.JsonBaseModel.to_json_obj_filter_defaults() -> JsonObj[Any] ⚓︎

Eject to JsonObj and filter key-values equal to (sub)class' default

Source code in libs/jsonbourne/jsonbourne/pydantic.py
210
211
212
def to_json_obj_filter_defaults(self) -> JsonObj[Any]:
    """Eject to JsonObj and filter key-values equal to (sub)class' default"""
    return JsonObj(self.to_dict_filter_defaults())
jsonbourne.pydantic.JsonBaseModel.to_json_obj_filter_none() -> JsonObj[Any] ⚓︎

Eject to JsonObj and filter key-values where the value is None

Source code in libs/jsonbourne/jsonbourne/pydantic.py
214
215
216
def to_json_obj_filter_none(self) -> JsonObj[Any]:
    """Eject to JsonObj and filter key-values where the value is None"""
    return JsonObj(self.to_dict_filter_none())
jsonbourne.pydantic.JsonBaseModel.validate_type(val: Any) -> JsonObj[_VT] classmethod ⚓︎

Validate and convert a value to a JsonObj object

Source code in libs/jsonbourne/jsonbourne/core.py
1064
1065
1066
1067
@classmethod
def validate_type(cls: Type[JsonObj[_VT]], val: Any) -> JsonObj[_VT]:
    """Validate and convert a value to a JsonObj object"""
    return cls(val)