_json_serializer.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. # Copyright 2023 Avaiga Private Limited
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
  4. # the License. You may obtain a copy of the License at
  5. #
  6. # http://www.apache.org/licenses/LICENSE-2.0
  7. #
  8. # Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
  9. # an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
  10. # specific language governing permissions and limitations under the License.
  11. import json # type: ignore
  12. from .._config import _Config
  13. from ..exceptions.exceptions import LoadingError
  14. from ._base_serializer import _BaseSerializer
  15. class _JsonSerializer(_BaseSerializer):
  16. """Convert configuration from JSON representation to Python Dict and reciprocally."""
  17. @classmethod
  18. def _write(cls, configuration: _Config, filename: str):
  19. with open(filename, "w") as fd:
  20. json.dump(cls._str(configuration), fd, ensure_ascii=False, indent=0, check_circular=False)
  21. @classmethod
  22. def _read(cls, filename: str) -> _Config:
  23. try:
  24. with open(filename) as f:
  25. config_as_dict = cls._pythonify(json.load(f))
  26. return cls._from_dict(config_as_dict)
  27. except json.JSONDecodeError as e:
  28. error_msg = f"Can not load configuration {e}"
  29. raise LoadingError(error_msg) from None
  30. @classmethod
  31. def _serialize(cls, configuration: _Config) -> str:
  32. return json.dumps(cls._str(configuration), ensure_ascii=False, indent=0, check_circular=False)
  33. @classmethod
  34. def _deserialize(cls, config_as_string: str) -> _Config:
  35. return cls._from_dict(cls._pythonify(dict(json.loads(config_as_string))))