Handle numpy types in the JSON message encoder

This commit is contained in:
Fabio Manganiello 2020-03-14 18:35:45 +01:00
parent e7084b5d6f
commit f2b3000922
2 changed files with 28 additions and 2 deletions

View file

@ -11,15 +11,41 @@ class Message(object):
""" Message generic class """
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 \
isinstance(obj, datetime.date) or \
isinstance(obj, datetime.time):
return obj.isoformat()
def default(self, obj):
value = self.parse_datetime(obj)
if value is not None:
return value
if isinstance(obj, set):
return list(obj)
value = self.parse_numpy(obj)
if value is not None:
return value
return super().default(obj)
def __init__(self, timestamp=None, *args, **kwargs):

View file

@ -182,7 +182,7 @@ class Event(Message):
'type': self.type,
**args
},
})
}, cls=self.Encoder)
class EventMatchResult(object):