Add custom JSONEncoder for subscribe_trigger WS endpoint (#48664)
This commit is contained in:
parent
324dd12db8
commit
7cc857a298
6 changed files with 66 additions and 69 deletions
|
@ -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)}
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue