Source code for sympathy.typeutils.json
# This file is part of Sympathy for Data.
# Copyright (c) 2017-2018, Combine Control Systems AB
#
# SYMPATHY FOR DATA COMMERCIAL LICENSE
# You should have received a link to the License with Sympathy for Data.
"""
API for working with the Json type.
Import this module like this::
from sympathy.api import json
Class :class:`json.Json`
--------------------------
.. autoclass:: Json
:members:
:special-members:
"""
import json
import numpy as np
from .. utils import filebase
from .. utils.context import inherit_doc
class NumpyEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, np.generic):
try:
return obj.tolist()
except Exception:
pass
elif isinstance(obj, np.ndarray):
try:
return obj.tolist()
except Exception:
pass
return super().default(obj)
[docs]
@filebase.typeutil('sytypealias json = sytext')
@inherit_doc
class Json(filebase.TypeAlias):
"""
A Json structure.
Any node port with the *Json* type will produce an object of this type.
"""
def set(self, data):
self._data.set(json.dumps(data, cls=NumpyEncoder))
def get(self):
return json.loads(self._data.get() or 'null')
[docs]
def source(self, other, shallow=False):
self.set(other.get())
[docs]
@classmethod
def viewer(cls):
from .. platform import json_viewer
return json_viewer.JsonViewer
[docs]
@classmethod
def icon(cls):
return 'ports/json.svg'
File = Json