mirror of
https://github.com/LonamiWebs/Telethon.git
synced 2025-02-09 16:10:51 +03:00
Add TLObject.to_json() for convenience
This commit is contained in:
parent
f1157b8fd1
commit
4ad9c9bf31
|
@ -1,8 +1,18 @@
|
||||||
import abc
|
import base64
|
||||||
|
import json
|
||||||
import struct
|
import struct
|
||||||
from datetime import datetime, date, timedelta
|
from datetime import datetime, date, timedelta
|
||||||
|
|
||||||
|
|
||||||
|
def _json_default(value):
|
||||||
|
if isinstance(value, bytes):
|
||||||
|
return base64.b64encode(value).decode('ascii')
|
||||||
|
elif isinstance(value, datetime):
|
||||||
|
return value.isoformat()
|
||||||
|
else:
|
||||||
|
return repr(value)
|
||||||
|
|
||||||
|
|
||||||
class TLObject:
|
class TLObject:
|
||||||
CONSTRUCTOR_ID = None
|
CONSTRUCTOR_ID = None
|
||||||
SUBCLASS_OF_ID = None
|
SUBCLASS_OF_ID = None
|
||||||
|
@ -144,6 +154,23 @@ class TLObject:
|
||||||
def to_dict(self):
|
def to_dict(self):
|
||||||
raise NotImplementedError
|
raise NotImplementedError
|
||||||
|
|
||||||
|
def to_json(self, fp=None, default=_json_default, **kwargs):
|
||||||
|
"""
|
||||||
|
Represent the current `TLObject` as JSON.
|
||||||
|
|
||||||
|
If ``fp`` is given, the JSON will be dumped to said
|
||||||
|
file pointer, otherwise a JSON string will be returned.
|
||||||
|
|
||||||
|
Note that bytes and datetimes cannot be represented
|
||||||
|
in JSON, so if those are found, they will be base64
|
||||||
|
encoded and ISO-formatted, respectively, by default.
|
||||||
|
"""
|
||||||
|
d = self.to_dict()
|
||||||
|
if fp:
|
||||||
|
return json.dump(d, fp, default=default, **kwargs)
|
||||||
|
else:
|
||||||
|
return json.dumps(d, default=default, **kwargs)
|
||||||
|
|
||||||
def __bytes__(self):
|
def __bytes__(self):
|
||||||
raise NotImplementedError
|
raise NotImplementedError
|
||||||
|
|
||||||
|
|
Loading…
Reference in New Issue
Block a user