Coverage for src/ipyvizzu/json.py: 100%
24 statements
« prev ^ index » next coverage.py v7.4.3, created at 2024-02-26 10:12 +0000
« prev ^ index » next coverage.py v7.4.3, created at 2024-02-26 10:12 +0000
1"""A module for working JavaScript code in json convertible objects."""
3import json
4from typing import Any, Optional
5import uuid
8class RawJavaScript:
9 """A class for representing raw JavaScript code."""
11 # pylint: disable=too-few-public-methods
13 def __init__(self, raw: Optional[str]):
14 """
15 RawJavaScript constructor.
17 It stores raw JavaScript code as a string.
19 Args:
20 raw: JavaScript code as `str`.
21 """
23 self._raw = raw
25 @property
26 def raw(self) -> Optional[str]:
27 """
28 A property for storing raw JavaScript code as a string.
30 Returns:
31 Raw JavaScript code as `str`.
32 """
34 return self._raw
37class RawJavaScriptEncoder(json.JSONEncoder):
38 """
39 A class for representing a custom json encoder,
40 it can encode objects that contain
41 [RawJavaScript][ipyvizzu.json.RawJavaScript] values.
42 """
44 def __init__(self, *args, **kwargs):
45 """
46 RawJavaScriptEncoder constructor.
48 It extends [JSONEncoder][json.JSONEncoder] with
49 an instance variable (`_raw_replacements`).
50 The `_raw_replacements` dictionary stores the `uuids` and
51 JavaScript codes of the [RawJavaScript][ipyvizzu.json.RawJavaScript] objects.
52 """
54 json.JSONEncoder.__init__(self, *args, **kwargs)
55 self._raw_replacements = {}
57 def default(self, o: Any):
58 """
59 Overrides [JSONEncoder.default][json.JSONEncoder.default] method.
60 It replaces [RawJavaScript][ipyvizzu.json.RawJavaScript] object with `uuid` and
61 it stores raw JavaScript code with `uuid` key in the `_raw_replacements` dictionary.
62 """
64 if isinstance(o, RawJavaScript):
65 key = uuid.uuid4().hex
66 self._raw_replacements[key] = o.raw
67 return key
68 return json.JSONEncoder.default(self, o)
70 def encode(self, o: Any):
71 """
72 Overrides [JSONEncoder.encode][json.JSONEncoder.encode] method.
73 It replaces `uuids` with raw JavaScript code without apostrophes.
74 """
76 result = json.JSONEncoder.encode(self, o)
77 for key, val in self._raw_replacements.items():
78 result = result.replace(f'"{key}"', val)
79 return result