From 3ebfb5602fa2f1503310a65eeed2519e635c98cb Mon Sep 17 00:00:00 2001 From: Nando Florestan Date: Mon, 7 Jun 2021 12:36:11 +0200 Subject: [PATCH] Add a simple json module to Transcrypt Most Python validation libraries use the json module. I am working on getting a validation library to work in the browser and in the server. This can solve the problem of keeping validation code in sync. --- transcrypt/modules/json.py | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 transcrypt/modules/json.py diff --git a/transcrypt/modules/json.py b/transcrypt/modules/json.py new file mode 100644 index 00000000..aada3b23 --- /dev/null +++ b/transcrypt/modules/json.py @@ -0,0 +1,36 @@ +"""The simplest cases of Python's json implemented with JS JSON. + +https://docs.python.org/3/library/json.html + +https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON +""" + + +class JSONDecodeError(ValueError): + """Exception raised when a JSON document cannot be parsed.""" + + def __init__(self, msg: str, doc): # noqa + # The interface is different in Python stdlib -- it has more variables, + # but we cannot do that because the SyntaxError object is different in + # each browser! + super().__init__(msg) + self.doc = doc # the thing we tried to parse + + +def loads(s: str): # noqa + # The Python stdlib function has lots of kwargs; we don't. + # We catch the JS SyntaxError and raise the python JSONDecodeError + # in an attempt to resemble Python behavior. + # __pragma__ ('ecom') # =================================================== + # __pragma__ ("js", "{}", "try {return JSON.parse(s);}\ncatch (exc) {\nconsole.error(exc);\nvar py_exc = new JSONDecodeError(exc.message, s);\npy_exc.__cause__ = null;\nthrow py_exc;\n}") + # __pragma__ ('noecom') # ================================================= + + +def dumps(obj) -> str: # noqa + # The Python stdlib function has lots of kwargs; we don't. + # JS: JSON.stringify(value, replacer, space) + result = JSON.stringify(obj, None, 2) + if result is js_undefined: + console.error("Not JSON serializable: ", obj) + raise ValueError("Object is not JSON serializable.") + return result