Add custom JSONEncoder for subscribe_trigger WS endpoint (#48664)

This commit is contained in:
Jason 2021-04-09 20:47:10 -07:00 committed by GitHub
parent 324dd12db8
commit 7cc857a298
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
6 changed files with 66 additions and 69 deletions

View file

@ -1,5 +1,5 @@
"""Helpers to help with encoding Home Assistant objects in JSON."""
from datetime import datetime
from datetime import datetime, timedelta
import json
from typing import Any
@ -20,3 +20,19 @@ class JSONEncoder(json.JSONEncoder):
return o.as_dict()
return json.JSONEncoder.default(self, o)
class ExtendedJSONEncoder(JSONEncoder):
"""JSONEncoder that supports Home Assistant objects and falls back to repr(o)."""
def default(self, o: Any) -> Any:
"""Convert certain objects.
Fall back to repr(o).
"""
if isinstance(o, timedelta):
return {"__type": str(type(o)), "total_seconds": o.total_seconds()}
try:
return super().default(o)
except TypeError:
return {"__type": str(type(o)), "repr": repr(o)}