json_utils ========== .. py:module:: quantify_scheduler.json_utils .. autoapi-nested-parse:: Module containing quantify JSON utilities. Module Contents --------------- Classes ~~~~~~~ .. autoapisummary:: quantify_scheduler.json_utils.JSONSchemaValMixin quantify_scheduler.json_utils.ScheduleJSONDecoder quantify_scheduler.json_utils.ScheduleJSONEncoder Functions ~~~~~~~~~ .. autoapisummary:: quantify_scheduler.json_utils.validate_json quantify_scheduler.json_utils.load_json_schema quantify_scheduler.json_utils.load_json_validator Attributes ~~~~~~~~~~ .. autoapisummary:: quantify_scheduler.json_utils.current_python_version quantify_scheduler.json_utils.lru_cache .. py:data:: current_python_version .. py:data:: lru_cache .. py:function:: validate_json(data, schema) Validate schema using jsonschema-rs .. py:function:: load_json_schema(relative_to: Union[str, pathlib.Path], filename: str) Load a JSON schema from file. Expects a 'schemas' directory in the same directory as `relative_to`. .. tip:: Typical usage of the form `schema = load_json_schema(__file__, 'definition.json')` :param relative_to: the file to begin searching from :param filename: the JSON file to load :returns: the schema :rtype: dict .. py:function:: load_json_validator(relative_to: Union[str, pathlib.Path], filename: str) -> Callable Load a JSON validator from file. Expects a 'schemas' directory in the same directory as `relative_to`. :param relative_to: the file to begin searching from :param filename: the JSON file to load :returns: The validator :rtype: Callable .. py:class:: JSONSchemaValMixin A mixin that adds validation utilities to classes that have a data attribute like a :class:`UserDict` based on JSONSchema. This requires the class to have a class variable "schema_filename" .. py:method:: is_valid(object_to_be_validated) -> bool :classmethod: Checks if the object is valid according to its schema :raises fastjsonschema.JsonSchemaException: if the data is invalid .. py:class:: ScheduleJSONDecoder(*args, **kwargs) Bases: :py:obj:`json.JSONDecoder` The Quantify Schedule JSONDecoder. The ScheduleJSONDecoder is used to convert a string with JSON content into a :class:`quantify_scheduler.schedules.schedule.Schedule`. To avoid the execution of malicious code ScheduleJSONDecoder uses :func:`ast.literal_eval` instead of :func:`eval` to convert the data to an instance of Schedule. Create new instance of ScheduleJSONDecoder to decode a string into a Schedule. The list of serializable classes can be extended with custom classes by providing the `modules` keyword argument. These classes have to implement :class:`quantify_scheduler.operations.operation.Operation` and overload the :code:`__str__` and :code:`__repr__` methods in order to serialize and deserialize domain objects into a valid JSON-format. :keyword modules: A list of custom modules containing serializable classes, by default [] :kwtype modules: List[ModuleType], *optional* .. py:attribute:: classes :type: Dict[str, Type[Any]] .. py:method:: decode_dict(obj: Dict[str, Any]) -> Union[Dict[str, Any], numpy.ndarray, type] Returns the deserialized JSON dictionary. :param obj: The dictionary to deserialize. :returns: The deserialized result. .. py:method:: custom_object_hook(obj: object) -> object The `object_hook` hook will be called with the result of every JSON object decoded and its return value will be used in place of the given ``dict``. :param obj: A pair of JSON objects. :returns: The deserialized result. .. py:class:: ScheduleJSONEncoder(*, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, default=None) Bases: :py:obj:`json.JSONEncoder` Custom JSONEncoder which encodes the quantify Schedule into a JSON file format string. Constructor for JSONEncoder, with sensible defaults. If skipkeys is false, then it is a TypeError to attempt encoding of keys that are not str, int, float or None. If skipkeys is True, such items are simply skipped. If ensure_ascii is true, the output is guaranteed to be str objects with all incoming non-ASCII characters escaped. If ensure_ascii is false, the output can contain non-ASCII characters. If check_circular is true, then lists, dicts, and custom encoded objects will be checked for circular references during encoding to prevent an infinite recursion (which would cause an RecursionError). Otherwise, no such check takes place. If allow_nan is true, then NaN, Infinity, and -Infinity will be encoded as such. This behavior is not JSON specification compliant, but is consistent with most JavaScript based encoders and decoders. Otherwise, it will be a ValueError to encode such floats. If sort_keys is true, then the output of dictionaries will be sorted by key; this is useful for regression tests to ensure that JSON serializations can be compared on a day-to-day basis. If indent is a non-negative integer, then JSON array elements and object members will be pretty-printed with that indent level. An indent level of 0 will only insert newlines. None is the most compact representation. If specified, separators should be an (item_separator, key_separator) tuple. The default is (', ', ': ') if *indent* is ``None`` and (',', ': ') otherwise. To get the most compact JSON representation, you should specify (',', ':') to eliminate whitespace. If specified, default is a function that gets called for objects that can't otherwise be serialized. It should return a JSON encodable version of the object or raise a ``TypeError``. .. py:method:: default(o) Overloads the json.JSONEncoder default method that returns a serializable object. It will try 3 different serialization methods which are, in order, check if the object is to be serialized to a string using repr. If not, try to use `__getstate__`. Finally, try to serialize the `__dict__` property.