diff --git a/docs/api_reference.md b/docs/api_reference.md index fdbb6453b..7e96ab5d0 100644 --- a/docs/api_reference.md +++ b/docs/api_reference.md @@ -42,6 +42,21 @@ some preprocessing on the Python code first. Either the resulting object or `None`. +### pyodide.as_nested_list(obj) + +Converts Javascript nested arrays to Python nested lists. This conversion can not +be performed automatically, because Javascript Arrays and Objects can be combined +in ways that are ambiguous. + +*Parameters* + +| name | type | description | +|--------|-------|-----------------------| +| *obj* | JS Object | The object to convert | + +*Returns* + +The object as nested Python lists. ## Javascript API diff --git a/src/pyodide.py b/src/pyodide.py index 5e45e8ed5..395a231ce 100644 --- a/src/pyodide.py +++ b/src/pyodide.py @@ -67,4 +67,16 @@ def find_imports(code): return list(imports) -__all__ = ['open_url', 'eval_code', 'find_imports'] +def as_nested_list(obj): + """ + Assumes a Javascript object is made of (possibly nested) arrays and + converts them to nested Python lists. + """ + try: + it = iter(obj) + return [as_nested_list(x) for x in it] + except TypeError: + return obj + + +__all__ = ['open_url', 'eval_code', 'find_imports', 'as_nested_list']