2Pure functions for converting Python values to JavaScript strings.
4We prioritise human-readability over absolute efficiency.
5For example, JSON is nicely indented to be more readable, rather than
6a compact encoding that uses less bytes on disk.
13class HumanReadableEncoder(json.JSONEncoder):
15 A custom JSON encoder with a few niceties for human-readability.
18 def encode(self, o: typing.Any) -> str:
20 Return a JSON string representation of a Python data structure, o.
22 if isinstance(o, list) and len(o) < 7 and len(json.dumps(o)) < 60:
25 return super().encode(o)
29 value: typing.Any, *, ensure_ascii: bool = False, sort_keys: bool = False
32 Convert a Python value to a JSON-encoded string.
38 ensure_ascii=ensure_ascii,
39 cls=HumanReadableEncoder,
47 ensure_ascii: bool = False,
48 sort_keys: bool = False,
51 Convert a Python value to a JSON-encoded JavaScript value.
53 json_string = encode_as_json(value, ensure_ascii=ensure_ascii, sort_keys=sort_keys)
54 js_string = f"const {varname} = {json_string};\n"