Created
August 6, 2020 05:07
-
-
Save raeq/5374ed3889c46ff6507e858af4e079bd to your computer and use it in GitHub Desktop.
Complex dictionaries to JSON
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from datetime import datetime | |
import json | |
class PythonObjectEncoder(json.JSONEncoder): | |
"""PythonObjectEncoder. | |
""" | |
def default(self, an_object_value): | |
"""default. | |
Args: | |
an_object_value: | |
""" | |
if isinstance(an_object_value, str): | |
return an_object_value | |
try: | |
iterable = iter(an_object_value) | |
return list(iterable) | |
except TypeError: | |
pass # this object is not iterable | |
if isinstance(an_object_value, datetime): | |
return an_object_value.isoformat() | |
elif hasattr(an_object_value, "__class__"): | |
return str(an_object_value.__dict__) | |
return super().default(an_object_value) | |
def dict_to_json(the_dict: dict) -> str: | |
"""dict_to_json. | |
Args: | |
the_dict (dict): the_dict | |
Returns: | |
str: | |
""" | |
return PythonObjectEncoder().encode(the_dict) | |
class SimpleClass: | |
"""simple_class. | |
""" | |
def __init__(self): | |
"""__init__. | |
""" | |
self.instance_value = 10 | |
b = SimpleClass() | |
dict1: dict = {} | |
dict1["string"] = "Hello, World!" | |
dict1["datetime"] = datetime(2030, 12, 31) | |
dict1["nothing"] = None | |
dict1["set"]: set = {0, 1, 2, 3} | |
dict1["tuple"] = ("apples", "fresh", "green") | |
dict1["list"] = ["a", "b", "c"] | |
dict1["simple_class"] = SimpleClass() | |
assert ( | |
dict_to_json(dict1) == | |
"""{"string": "Hello, World!", "datetime": "2030-12-31T00:00:00", "nothing": null, "set": [0, 1, 2, 3], "tuple": ["apples", "fresh", "green"], "list": ["a", "b", "c"], "user_class": "{'instance_value': 10}"}""" | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment