[+] Enhanced JSON
This commit is contained in:
@@ -1,5 +1,10 @@
|
|||||||
__version__ = "1.0.0"
|
__version__ = "1.0.0"
|
||||||
|
|
||||||
|
import dataclasses
|
||||||
|
import json
|
||||||
|
from datetime import datetime, date
|
||||||
|
from typing import Union
|
||||||
|
|
||||||
|
|
||||||
def ansi_rgb(r: int, g: int, b: int, foreground: bool = True) -> str:
|
def ansi_rgb(r: int, g: int, b: int, foreground: bool = True) -> str:
|
||||||
"""
|
"""
|
||||||
@@ -80,3 +85,43 @@ def parse_date_only(iso: str) -> datetime:
|
|||||||
:return: Datetime object
|
:return: Datetime object
|
||||||
"""
|
"""
|
||||||
return datetime(int(iso[:4]), int(iso[5:7]), int(iso[8:10]))
|
return datetime(int(iso[:4]), int(iso[5:7]), int(iso[8:10]))
|
||||||
|
|
||||||
|
|
||||||
|
class EnhancedJSONEncoder(json.JSONEncoder):
|
||||||
|
"""
|
||||||
|
An improvement to the json.JSONEncoder class, which supports:
|
||||||
|
encoding for dataclasses, encoding for datetime, and sets
|
||||||
|
"""
|
||||||
|
|
||||||
|
def default(self, o: object) -> object:
|
||||||
|
|
||||||
|
# Support encoding dataclasses
|
||||||
|
# https://stackoverflow.com/a/51286749/7346633
|
||||||
|
if dataclasses.is_dataclass(o):
|
||||||
|
return dataclasses.asdict(o)
|
||||||
|
|
||||||
|
# Support encoding datetime
|
||||||
|
if isinstance(o, (datetime, date)):
|
||||||
|
return o.isoformat()
|
||||||
|
|
||||||
|
# Support for sets
|
||||||
|
# https://stackoverflow.com/a/8230505/7346633
|
||||||
|
if isinstance(o, set):
|
||||||
|
return list(o)
|
||||||
|
|
||||||
|
return super().default(o)
|
||||||
|
|
||||||
|
|
||||||
|
def json_stringify(obj: object, indent: Union[int, None] = None) -> str:
|
||||||
|
"""
|
||||||
|
Serialize json string with support for dataclasses and datetime and sets and with custom
|
||||||
|
configuration.
|
||||||
|
|
||||||
|
Preconditions:
|
||||||
|
- obj != None
|
||||||
|
|
||||||
|
:param obj: Objects
|
||||||
|
:param indent: Indent size or none
|
||||||
|
:return: Json strings
|
||||||
|
"""
|
||||||
|
return json.dumps(obj, indent=indent, cls=EnhancedJSONEncoder, ensure_ascii=False)
|
||||||
|
|||||||
Reference in New Issue
Block a user