Handle numpy types in the JSON message encoder
This commit is contained in:
parent
e7084b5d6f
commit
f2b3000922
2 changed files with 28 additions and 2 deletions
|
@ -11,15 +11,41 @@ class Message(object):
|
||||||
""" Message generic class """
|
""" Message generic class """
|
||||||
|
|
||||||
class Encoder(json.JSONEncoder):
|
class Encoder(json.JSONEncoder):
|
||||||
def default(self, obj):
|
@staticmethod
|
||||||
|
def parse_numpy(obj):
|
||||||
|
try:
|
||||||
|
import numpy as np
|
||||||
|
except ImportError:
|
||||||
|
return
|
||||||
|
|
||||||
|
if isinstance(obj, np.floating):
|
||||||
|
return float(obj)
|
||||||
|
if isinstance(obj, np.integer):
|
||||||
|
return int(obj)
|
||||||
|
if isinstance(obj, np.ndarray):
|
||||||
|
return obj.tolist()
|
||||||
|
|
||||||
|
return
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def parse_datetime(obj):
|
||||||
if isinstance(obj, datetime.datetime) or \
|
if isinstance(obj, datetime.datetime) or \
|
||||||
isinstance(obj, datetime.date) or \
|
isinstance(obj, datetime.date) or \
|
||||||
isinstance(obj, datetime.time):
|
isinstance(obj, datetime.time):
|
||||||
return obj.isoformat()
|
return obj.isoformat()
|
||||||
|
|
||||||
|
def default(self, obj):
|
||||||
|
value = self.parse_datetime(obj)
|
||||||
|
if value is not None:
|
||||||
|
return value
|
||||||
|
|
||||||
if isinstance(obj, set):
|
if isinstance(obj, set):
|
||||||
return list(obj)
|
return list(obj)
|
||||||
|
|
||||||
|
value = self.parse_numpy(obj)
|
||||||
|
if value is not None:
|
||||||
|
return value
|
||||||
|
|
||||||
return super().default(obj)
|
return super().default(obj)
|
||||||
|
|
||||||
def __init__(self, timestamp=None, *args, **kwargs):
|
def __init__(self, timestamp=None, *args, **kwargs):
|
||||||
|
|
|
@ -182,7 +182,7 @@ class Event(Message):
|
||||||
'type': self.type,
|
'type': self.type,
|
||||||
**args
|
**args
|
||||||
},
|
},
|
||||||
})
|
}, cls=self.Encoder)
|
||||||
|
|
||||||
|
|
||||||
class EventMatchResult(object):
|
class EventMatchResult(object):
|
||||||
|
|
Loading…
Reference in a new issue