|
|
|
@ -14,7 +14,17 @@ def default(obj: Any) -> Any:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def dumps(obj: Any, *, pretty: bool = False, **kwargs: Any) -> str:
|
|
|
|
|
"""Return a json string representation of an object."""
|
|
|
|
|
"""Return a json string representation of an object.
|
|
|
|
|
|
|
|
|
|
Args:
|
|
|
|
|
obj: The object to dump
|
|
|
|
|
pretty: Whether to pretty print the json. If true, the json will be
|
|
|
|
|
indented with 2 spaces (if no indent is provided as part of kwargs)
|
|
|
|
|
**kwargs: Additional arguments to pass to json.dumps
|
|
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
|
A json string representation of the object
|
|
|
|
|
"""
|
|
|
|
|
if "default" in kwargs:
|
|
|
|
|
raise ValueError("`default` should not be passed to dumps")
|
|
|
|
|
try:
|
|
|
|
@ -25,11 +35,24 @@ def dumps(obj: Any, *, pretty: bool = False, **kwargs: Any) -> str:
|
|
|
|
|
return json.dumps(obj, default=default, **kwargs)
|
|
|
|
|
except TypeError:
|
|
|
|
|
if pretty:
|
|
|
|
|
indent = kwargs.pop("indent", 2)
|
|
|
|
|
return json.dumps(to_json_not_implemented(obj), indent=indent, **kwargs)
|
|
|
|
|
else:
|
|
|
|
|
return json.dumps(to_json_not_implemented(obj), **kwargs)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def dumpd(obj: Any) -> Dict[str, Any]:
|
|
|
|
|
"""Return a json dict representation of an object."""
|
|
|
|
|
"""Return a dict representation of an object.
|
|
|
|
|
|
|
|
|
|
Note:
|
|
|
|
|
Unfortunately this function is not as efficient as it could be
|
|
|
|
|
because it first dumps the object to a json string and then loads it
|
|
|
|
|
back into a dictionary.
|
|
|
|
|
|
|
|
|
|
Args:
|
|
|
|
|
obj: The object to dump.
|
|
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
|
dictionary that can be serialized to json using json.dumps
|
|
|
|
|
"""
|
|
|
|
|
return json.loads(dumps(obj))
|
|
|
|
|