Skip to content

JsonModule ⚓︎

JsonModule()

JSON class meant to mimic the js/ts-JSON

Methods:

  • binify

    Return JSON string bytes for given data

  • dumpb

    Return JSON string bytes for given data

  • dumps

    Return JSON stringified/dumps-ed data

  • json_lib

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

  • jsonify

    Alias for jsonbourne.core.jsonify

  • loads

    Parse JSON string/bytes and return raw representation

  • parse

    Parse JSON string/bytes

  • rjson

    Read JSON file and return raw representation

  • stringify

    Return JSON stringified/dumps-ed data

  • unjsonify

    Alias for jsonbourne.core.unjsonify

  • which

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

  • wjson

    Write JSON file

binify staticmethod ⚓︎

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

dumpb staticmethod ⚓︎

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

dumps staticmethod ⚓︎

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

json_lib staticmethod ⚓︎

json_lib() -> str

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

jsonify staticmethod ⚓︎

jsonify(value: Any) -> Any

Alias for jsonbourne.core.jsonify

loads staticmethod ⚓︎

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

parse staticmethod ⚓︎

parse(
    string: Union[bytes, str],
    obj: bool = False,
    jsonc: bool = False,
    jsonl: bool = False,
    ndjson: bool = False,
    **kwargs: Any,
) -> Any

Parse JSON string/bytes

rjson staticmethod ⚓︎

rjson(
    fspath: Union[Path, str],
    jsonc: bool = False,
    jsonl: bool = False,
    ndjson: bool = False,
    **kwargs: Any,
) -> Any

Read JSON file and return raw representation

stringify staticmethod ⚓︎

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

unjsonify staticmethod ⚓︎

unjsonify(value: Any) -> Any

Alias for jsonbourne.core.unjsonify

which staticmethod ⚓︎

which() -> str

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

wjson staticmethod ⚓︎

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

jsonbourne ⚓︎

jsonbourne the best undercover json lib

Dynamic Graphics Python

Modules:

  • core

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

  • dev

    jsonbourne.dev

  • fastapi
  • helpers

    JSONBourne helper funks and utils

  • httpx

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

  • json_arr
  • jsonlib

    jsonbourne jsonlib api

  • pydantic

    JSONBourne + Pydantic

  • trydantic

    trydantic = try + pydantic

Classes:

  • JsonDict

    Alias for JsonObj

  • JsonObj

    JSON friendly python dictionary with dot notation and string only keys

Functions:

  • rm_js_comments

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

JsonDict ⚓︎

JsonDict(*args: Dict[_KT, _VT])
JsonDict(*args: Dict[_KT, _VT], **kwargs: _VT)
JsonDict(*args: Mapping[_KT, _VT])
JsonDict(*args: Mapping[_KT, _VT], **kwargs: _VT)
JsonDict(*args: Any, **kwargs: _VT)

Bases: JsonObj[_VT], Generic[_VT]

Alias for JsonObj

Methods:

  • JSON

    Return JSON string of the JsonObj object (and children)

  • asdict

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

  • dot_items

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

  • dot_items_list

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

  • dot_keys

    Yield the JsonObj's dot-notation keys

  • dot_keys_list

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

  • dot_keys_set

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

  • dot_lookup

    Look up JsonObj keys using dot notation as a string

  • eject

    Eject to python-builtin dictionary object

  • entries

    Alias for items

  • filter_false

    Filter key-values where the value is false-y

  • filter_none

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

  • from_dict

    Return a JsonObj object from a dictionary of data

  • from_json

    Return a JsonObj object from a json string

  • items

    Return an items view of the JsonObj object

  • keys

    Return the keys view of the JsonObj object

  • recurse

    Recursively convert all sub dictionaries to JsonObj objects

  • stringify

    Return JSON string of the JsonObj object (and children)

  • to_dict

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

  • to_json

    Return JSON string of the JsonObj object (and children)

  • to_str

    Return a string representation of the JsonObj object

  • validate_type

    Validate and convert a value to a JsonObj object

JSON ⚓︎

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)

Parameters:

  • fmt ⚓︎

    (bool, default: False ) –

    If True, return a JSON string with newlines and indentation

  • pretty ⚓︎

    (bool, default: False ) –

    If True, return a JSON string with newlines and indentation

  • sort_keys ⚓︎

    (bool, default: False ) –

    Sort dictionary keys if True

  • append_newline ⚓︎

    (bool, default: False ) –

    Append a newline 'n' to JSON string if True

  • default ⚓︎

    (Optional[Callable[[Any], Any]], default: None ) –

    default function hook for JSON serialization

  • **kwargs ⚓︎

    (Any, default: {} ) –

    additional kwargs to be passed down to jsonlib.dumps

Returns:

  • str ( str ) –

    JSON string of the JsonObj object

asdict ⚓︎

asdict() -> Dict[_KT, Any]

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

dot_items ⚓︎

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

dot_items_list ⚓︎

dot_items_list() -> List[Tuple[Tuple[str, ...], Any]]

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

dot_keys ⚓︎

dot_keys() -> Iterable[Tuple[str, ...]]

Yield the JsonObj's dot-notation keys

Returns:

  • 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

dot_keys_list ⚓︎

dot_keys_list(
    sort_keys: bool = False,
) -> List[Tuple[str, ...]]

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

Parameters:

  • sort_keys ⚓︎

    (bool, default: False ) –

    Flag to have the dot-keys be returned sorted

Returns:

  • List[Tuple[str, ...]]

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

dot_keys_set ⚓︎

dot_keys_set() -> Set[Tuple[str, ...]]

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

Returns:

  • Set[Tuple[str, ...]]

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

dot_lookup ⚓︎

dot_lookup(
    key: Union[str, Tuple[str, ...], List[str]],
) -> Any

Look up JsonObj keys using dot notation as a string

Parameters:

  • key ⚓︎

    (str) –

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

Returns:

  • Any

    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]

eject ⚓︎

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'>

entries ⚓︎

entries() -> ItemsView[_KT, _VT]

Alias for items

filter_false ⚓︎

filter_false(recursive: bool = False) -> JsonObj[_VT]

Filter key-values where the value is false-y

Parameters:

  • recursive ⚓︎

    (bool, default: False ) –

    Recurse into sub JsonObjs and dictionaries

Returns:

  • 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'}
})

filter_none ⚓︎

filter_none(recursive: bool = False) -> JsonObj[_VT]

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

Parameters:

  • recursive ⚓︎

    (bool, default: False ) –

    Recursively filter out None values

Returns:

  • 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
})

from_dict classmethod ⚓︎

from_dict(data: Dict[_KT, _VT]) -> JsonObj[_VT]

Return a JsonObj object from a dictionary of data

from_json classmethod ⚓︎

from_json(json_string: Union[bytes, str]) -> JsonObj[_VT]

Return a JsonObj object from a json string

Parameters:

  • json_string ⚓︎

    (str) –

    JSON string to convert to a JsonObj

Returns:

  • JsonObjT ( JsonObj[_VT] ) –

    JsonObj object for the given JSON string

items ⚓︎

items() -> ItemsView[_KT, _VT]

Return an items view of the JsonObj object

keys ⚓︎

keys() -> KeysView[_KT]

Return the keys view of the JsonObj object

recurse ⚓︎

recurse() -> None

Recursively convert all sub dictionaries to JsonObj objects

stringify ⚓︎

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)

Parameters:

  • fmt ⚓︎

    (bool, default: False ) –

    If True, return a JSON string with newlines and indentation

  • pretty ⚓︎

    (bool, default: False ) –

    If True, return a JSON string with newlines and indentation

  • sort_keys ⚓︎

    (bool, default: False ) –

    Sort dictionary keys if True

  • append_newline ⚓︎

    (bool, default: False ) –

    Append a newline 'n' to JSON string if True

  • default ⚓︎

    (Optional[Callable[[Any], Any]], default: None ) –

    default function hook for JSON serialization

  • **kwargs ⚓︎

    (Any, default: {} ) –

    additional kwargs to be passed down to jsonlib.dumps

Returns:

  • str ( str ) –

    JSON string of the JsonObj object

to_dict ⚓︎

to_dict() -> Dict[_KT, Any]

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

to_json ⚓︎

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)

Parameters:

  • fmt ⚓︎

    (bool, default: False ) –

    If True, return a JSON string with newlines and indentation

  • pretty ⚓︎

    (bool, default: False ) –

    If True, return a JSON string with newlines and indentation

  • sort_keys ⚓︎

    (bool, default: False ) –

    Sort dictionary keys if True

  • append_newline ⚓︎

    (bool, default: False ) –

    Append a newline 'n' to JSON string if True

  • default ⚓︎

    (Optional[Callable[[Any], Any]], default: None ) –

    default function hook for JSON serialization

  • **kwargs ⚓︎

    (Any, default: {} ) –

    additional kwargs to be passed down to jsonlib.dumps

Returns:

  • str ( str ) –

    JSON string of the JsonObj object

to_str ⚓︎

to_str(
    minify: bool = False, width: Optional[int] = None
) -> str

Return a string representation of the JsonObj object

validate_type classmethod ⚓︎

validate_type(val: Any) -> JsonObj[_VT]

Validate and convert a value to a JsonObj object

JsonObj ⚓︎

JsonObj(*args: Dict[_KT, _VT])
JsonObj(*args: Dict[_KT, _VT], **kwargs: _VT)
JsonObj(*args: Mapping[_KT, _VT])
JsonObj(*args: Mapping[_KT, _VT], **kwargs: _VT)
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}]}

Methods:

  • JSON

    Return JSON string of the JsonObj object (and children)

  • asdict

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

  • dot_items

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

  • dot_items_list

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

  • dot_keys

    Yield the JsonObj's dot-notation keys

  • dot_keys_list

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

  • dot_keys_set

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

  • dot_lookup

    Look up JsonObj keys using dot notation as a string

  • eject

    Eject to python-builtin dictionary object

  • entries

    Alias for items

  • filter_false

    Filter key-values where the value is false-y

  • filter_none

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

  • from_dict

    Return a JsonObj object from a dictionary of data

  • from_json

    Return a JsonObj object from a json string

  • items

    Return an items view of the JsonObj object

  • keys

    Return the keys view of the JsonObj object

  • recurse

    Recursively convert all sub dictionaries to JsonObj objects

  • stringify

    Return JSON string of the JsonObj object (and children)

  • to_dict

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

  • to_json

    Return JSON string of the JsonObj object (and children)

  • to_str

    Return a string representation of the JsonObj object

  • validate_type

    Validate and convert a value to a JsonObj object

JSON ⚓︎

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)

Parameters:

  • fmt ⚓︎

    (bool, default: False ) –

    If True, return a JSON string with newlines and indentation

  • pretty ⚓︎

    (bool, default: False ) –

    If True, return a JSON string with newlines and indentation

  • sort_keys ⚓︎

    (bool, default: False ) –

    Sort dictionary keys if True

  • append_newline ⚓︎

    (bool, default: False ) –

    Append a newline 'n' to JSON string if True

  • default ⚓︎

    (Optional[Callable[[Any], Any]], default: None ) –

    default function hook for JSON serialization

  • **kwargs ⚓︎

    (Any, default: {} ) –

    additional kwargs to be passed down to jsonlib.dumps

Returns:

  • str ( str ) –

    JSON string of the JsonObj object

asdict ⚓︎

asdict() -> Dict[_KT, Any]

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

dot_items ⚓︎

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

dot_items_list ⚓︎

dot_items_list() -> List[Tuple[Tuple[str, ...], Any]]

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

dot_keys ⚓︎

dot_keys() -> Iterable[Tuple[str, ...]]

Yield the JsonObj's dot-notation keys

Returns:

  • 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

dot_keys_list ⚓︎

dot_keys_list(
    sort_keys: bool = False,
) -> List[Tuple[str, ...]]

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

Parameters:

  • sort_keys ⚓︎

    (bool, default: False ) –

    Flag to have the dot-keys be returned sorted

Returns:

  • List[Tuple[str, ...]]

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

dot_keys_set ⚓︎

dot_keys_set() -> Set[Tuple[str, ...]]

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

Returns:

  • Set[Tuple[str, ...]]

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

dot_lookup ⚓︎

dot_lookup(
    key: Union[str, Tuple[str, ...], List[str]],
) -> Any

Look up JsonObj keys using dot notation as a string

Parameters:

  • key ⚓︎

    (str) –

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

Returns:

  • Any

    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]

eject ⚓︎

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'>

entries ⚓︎

entries() -> ItemsView[_KT, _VT]

Alias for items

filter_false ⚓︎

filter_false(recursive: bool = False) -> JsonObj[_VT]

Filter key-values where the value is false-y

Parameters:

  • recursive ⚓︎

    (bool, default: False ) –

    Recurse into sub JsonObjs and dictionaries

Returns:

  • 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'}
})

filter_none ⚓︎

filter_none(recursive: bool = False) -> JsonObj[_VT]

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

Parameters:

  • recursive ⚓︎

    (bool, default: False ) –

    Recursively filter out None values

Returns:

  • 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
})

from_dict classmethod ⚓︎

from_dict(data: Dict[_KT, _VT]) -> JsonObj[_VT]

Return a JsonObj object from a dictionary of data

from_json classmethod ⚓︎

from_json(json_string: Union[bytes, str]) -> JsonObj[_VT]

Return a JsonObj object from a json string

Parameters:

  • json_string ⚓︎

    (str) –

    JSON string to convert to a JsonObj

Returns:

  • JsonObjT ( JsonObj[_VT] ) –

    JsonObj object for the given JSON string

items ⚓︎

items() -> ItemsView[_KT, _VT]

Return an items view of the JsonObj object

keys ⚓︎

keys() -> KeysView[_KT]

Return the keys view of the JsonObj object

recurse ⚓︎

recurse() -> None

Recursively convert all sub dictionaries to JsonObj objects

stringify ⚓︎

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)

Parameters:

  • fmt ⚓︎

    (bool, default: False ) –

    If True, return a JSON string with newlines and indentation

  • pretty ⚓︎

    (bool, default: False ) –

    If True, return a JSON string with newlines and indentation

  • sort_keys ⚓︎

    (bool, default: False ) –

    Sort dictionary keys if True

  • append_newline ⚓︎

    (bool, default: False ) –

    Append a newline 'n' to JSON string if True

  • default ⚓︎

    (Optional[Callable[[Any], Any]], default: None ) –

    default function hook for JSON serialization

  • **kwargs ⚓︎

    (Any, default: {} ) –

    additional kwargs to be passed down to jsonlib.dumps

Returns:

  • str ( str ) –

    JSON string of the JsonObj object

to_dict ⚓︎

to_dict() -> Dict[_KT, Any]

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

to_json ⚓︎

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)

Parameters:

  • fmt ⚓︎

    (bool, default: False ) –

    If True, return a JSON string with newlines and indentation

  • pretty ⚓︎

    (bool, default: False ) –

    If True, return a JSON string with newlines and indentation

  • sort_keys ⚓︎

    (bool, default: False ) –

    Sort dictionary keys if True

  • append_newline ⚓︎

    (bool, default: False ) –

    Append a newline 'n' to JSON string if True

  • default ⚓︎

    (Optional[Callable[[Any], Any]], default: None ) –

    default function hook for JSON serialization

  • **kwargs ⚓︎

    (Any, default: {} ) –

    additional kwargs to be passed down to jsonlib.dumps

Returns:

  • str ( str ) –

    JSON string of the JsonObj object

to_str ⚓︎

to_str(
    minify: bool = False, width: Optional[int] = None
) -> str

Return a string representation of the JsonObj object

validate_type classmethod ⚓︎

validate_type(val: Any) -> JsonObj[_VT]

Validate and convert a value to a JsonObj object

rm_js_comments ⚓︎

rm_js_comments(string: str) -> str

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

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


pydantic ⚓︎

JSONBourne + Pydantic

Classes:

  • JsonBaseConfig

    Pydantic v1 model config class for JsonBaseModel; can be overridden

  • JsonBaseModel

    Hybrid pydantic.BaseModel and jsonbourne.JsonObj

JsonBaseConfig ⚓︎

Pydantic v1 model config class for JsonBaseModel; can be overridden

JsonBaseModel ⚓︎

JsonBaseModel(*args: Dict[_KT, _VT])
JsonBaseModel(*args: Dict[_KT, _VT], **kwargs: _VT)
JsonBaseModel(*args: Mapping[_KT, _VT])
JsonBaseModel(*args: Mapping[_KT, _VT], **kwargs: _VT)
JsonBaseModel(*args: Any, **kwargs: _VT)

Bases: BaseModel, JsonObj, MutableMapping

Hybrid pydantic.BaseModel and jsonbourne.JsonObj

Methods:

  • asdict

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

  • defaults_dict

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

  • dict

    Alias for model_dump

  • dot_items

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

  • dot_items_list

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

  • dot_keys

    Yield the JsonObj's dot-notation keys

  • dot_keys_list

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

  • dot_keys_set

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

  • dot_lookup

    Look up JsonObj keys using dot notation as a string

  • eject

    Eject to python-builtin dictionary object

  • entries

    Alias for items

  • filter_false

    Filter key-values where the value is false-y

  • filter_none

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

  • from_dict

    Return a JsonObj object from a dictionary of data

  • from_dict_filtered

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

  • from_json

    Return a JsonObj object from a json string

  • has_required_fields

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

  • is_default

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

  • items

    Return an items view of the JsonObj object

  • json

    Alias for model_dumps

  • keys

    Return the keys view of the JsonObj object

  • recurse

    Recursively convert all sub dictionaries to JsonObj objects

  • stringify

    Return JSON string of the JsonObj object (and children)

  • to_dict

    Eject and return object as plain jane dictionary

  • to_dict_filter_defaults

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

  • to_dict_filter_none

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

  • to_json

    Return JSON string of the JsonObj object (and children)

  • to_json_dict

    Eject object and sub-objects to jsonbourne.JsonObj

  • to_json_obj

    Eject object and sub-objects to jsonbourne.JsonObj

  • to_json_obj_filter_defaults

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

  • to_json_obj_filter_none

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

  • validate_type

    Validate and convert a value to a JsonObj object

asdict ⚓︎

asdict() -> Dict[_KT, Any]

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

defaults_dict classmethod ⚓︎

defaults_dict() -> Dict[str, Any]

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

Returns:

  • 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'}

dict ⚓︎

dict(*args: Any, **kwargs: Any) -> Dict[str, Any]

Alias for model_dump

dot_items ⚓︎

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

dot_items_list ⚓︎

dot_items_list() -> List[Tuple[Tuple[str, ...], Any]]

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

dot_keys ⚓︎

dot_keys() -> Iterable[Tuple[str, ...]]

Yield the JsonObj's dot-notation keys

Returns:

  • 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

dot_keys_list ⚓︎

dot_keys_list(
    sort_keys: bool = False,
) -> List[Tuple[str, ...]]

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

Parameters:

  • sort_keys ⚓︎

    (bool, default: False ) –

    Flag to have the dot-keys be returned sorted

Returns:

  • List[Tuple[str, ...]]

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

dot_keys_set ⚓︎

dot_keys_set() -> Set[Tuple[str, ...]]

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

Returns:

  • Set[Tuple[str, ...]]

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

dot_lookup ⚓︎

dot_lookup(
    key: Union[str, Tuple[str, ...], List[str]],
) -> Any

Look up JsonObj keys using dot notation as a string

Parameters:

  • key ⚓︎

    (str) –

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

Returns:

  • Any

    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]

eject ⚓︎

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'>

entries ⚓︎

entries() -> ItemsView[_KT, _VT]

Alias for items

filter_false ⚓︎

filter_false(recursive: bool = False) -> JsonObj[_VT]

Filter key-values where the value is false-y

Parameters:

  • recursive ⚓︎

    (bool, default: False ) –

    Recurse into sub JsonObjs and dictionaries

Returns:

  • 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'}
})

filter_none ⚓︎

filter_none(recursive: bool = False) -> JsonObj[_VT]

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

Parameters:

  • recursive ⚓︎

    (bool, default: False ) –

    Recursively filter out None values

Returns:

  • 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
})

from_dict classmethod ⚓︎

from_dict(data: Dict[_KT, _VT]) -> JsonObj[_VT]

Return a JsonObj object from a dictionary of data

from_dict_filtered classmethod ⚓︎

from_dict_filtered(
    dictionary: Dict[str, Any],
) -> JsonBaseModelT

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

from_json classmethod ⚓︎

from_json(json_string: Union[bytes, str]) -> JsonObj[_VT]

Return a JsonObj object from a json string

Parameters:

  • json_string ⚓︎

    (str) –

    JSON string to convert to a JsonObj

Returns:

  • JsonObjT ( JsonObj[_VT] ) –

    JsonObj object for the given JSON string

has_required_fields classmethod ⚓︎

has_required_fields() -> bool

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

Returns:

  • bool ( bool ) –

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

is_default ⚓︎

is_default() -> bool

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

Returns:

  • 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

items ⚓︎

items() -> ItemsView[_KT, _VT]

Return an items view of the JsonObj object

json ⚓︎

json(*args: Any, **kwargs: Any) -> str

Alias for model_dumps

keys ⚓︎

keys() -> KeysView[_KT]

Return the keys view of the JsonObj object

recurse ⚓︎

recurse() -> None

Recursively convert all sub dictionaries to JsonObj objects

stringify ⚓︎

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)

Parameters:

  • fmt ⚓︎

    (bool, default: False ) –

    If True, return a JSON string with newlines and indentation

  • pretty ⚓︎

    (bool, default: False ) –

    If True, return a JSON string with newlines and indentation

  • sort_keys ⚓︎

    (bool, default: False ) –

    Sort dictionary keys if True

  • append_newline ⚓︎

    (bool, default: False ) –

    Append a newline 'n' to JSON string if True

  • default ⚓︎

    (Optional[Callable[[Any], Any]], default: None ) –

    default function hook for JSON serialization

  • **kwargs ⚓︎

    (Any, default: {} ) –

    additional kwargs to be passed down to jsonlib.dumps

Returns:

  • str ( str ) –

    JSON string of the JsonObj object

to_dict ⚓︎

to_dict() -> Dict[str, Any]

Eject and return object as plain jane dictionary

to_dict_filter_defaults ⚓︎

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})

to_dict_filter_none ⚓︎

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'})

to_json ⚓︎

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)

Parameters:

  • fmt ⚓︎

    (bool, default: False ) –

    If True, return a JSON string with newlines and indentation

  • pretty ⚓︎

    (bool, default: False ) –

    If True, return a JSON string with newlines and indentation

  • sort_keys ⚓︎

    (bool, default: False ) –

    Sort dictionary keys if True

  • append_newline ⚓︎

    (bool, default: False ) –

    Append a newline 'n' to JSON string if True

  • default ⚓︎

    (Optional[Callable[[Any], Any]], default: None ) –

    default function hook for JSON serialization

  • **kwargs ⚓︎

    (Any, default: {} ) –

    additional kwargs to be passed down to jsonlib.dumps

Returns:

  • str ( str ) –

    JSON string of the JsonObj object

to_json_dict ⚓︎

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'>

to_json_obj ⚓︎

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'>

to_json_obj_filter_defaults ⚓︎

to_json_obj_filter_defaults() -> JsonObj[Any]

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

to_json_obj_filter_none ⚓︎

to_json_obj_filter_none() -> JsonObj[Any]

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

validate_type classmethod ⚓︎

validate_type(val: Any) -> JsonObj[_VT]

Validate and convert a value to a JsonObj object