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
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
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
⚓︎
Return the JsonObj object (and children) as a python dictionary
dot_items
⚓︎
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
⚓︎
Return list of tuples of the form (dot-key, value)
dot_keys
⚓︎
Yield the JsonObj's dot-notation keys
Returns:
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_set
⚓︎
dot_lookup
⚓︎
Look up JsonObj keys using dot notation as a string
Parameters:
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'>
filter_false
⚓︎
Filter key-values where the value is false-y
Parameters:
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 key-values where the value is None
but not false-y
Parameters:
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
⚓︎
Return a JsonObj object from a dictionary of data
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
⚓︎
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
⚓︎
Return a string representation of the 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
⚓︎
Return the JsonObj object (and children) as a python dictionary
dot_items
⚓︎
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
⚓︎
Return list of tuples of the form (dot-key, value)
dot_keys
⚓︎
Yield the JsonObj's dot-notation keys
Returns:
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_set
⚓︎
dot_lookup
⚓︎
Look up JsonObj keys using dot notation as a string
Parameters:
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'>
filter_false
⚓︎
Filter key-values where the value is false-y
Parameters:
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 key-values where the value is None
but not false-y
Parameters:
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
⚓︎
Return a JsonObj object from a dictionary of data
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
⚓︎
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
⚓︎
Return a string representation of the JsonObj object
rm_js_comments
⚓︎
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
andjsonbourne.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
⚓︎
Return the JsonObj object (and children) as a python dictionary
defaults_dict
classmethod
⚓︎
Return a dictionary of non-required keys -> default value(s)
Returns:
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'}
dot_items
⚓︎
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
⚓︎
Return list of tuples of the form (dot-key, value)
dot_keys
⚓︎
Yield the JsonObj's dot-notation keys
Returns:
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_set
⚓︎
dot_lookup
⚓︎
Look up JsonObj keys using dot notation as a string
Parameters:
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'>
filter_false
⚓︎
Filter key-values where the value is false-y
Parameters:
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 key-values where the value is None
but not false-y
Parameters:
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
⚓︎
Return a JsonObj object from a dictionary of data
from_dict_filtered
classmethod
⚓︎
Create class from dict filtering keys not in (sub)class' fields
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
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_filter_defaults
⚓︎
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
⚓︎
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
⚓︎
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
⚓︎
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
⚓︎
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