Created
August 6, 2020 05:23
-
-
Save raeq/d7d6e1b9bede6301b3e5377ac20c9e98 to your computer and use it in GitHub Desktop.
Complex dictionary 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
import json | |
from datetime import datetime | |
class PythonObjectEncoder(json.JSONEncoder): | |
def default(self, 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 an_object_value.__dict__ | |
return super().default(an_object_value) | |
def dict_to_json(the_dict: dict) -> str: | |
return PythonObjectEncoder().encode(the_dict) | |
class SimpleClass: | |
def __init__(self): | |
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"],' | |
' "simple_class": {"instance_value": 10}}' | |
) | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment