Convert Python %SYS.Python List to %Library.DynamicArray in Objectscript
As part of a recent documentation technical project to optimize the search, I needed to use Embedded Python in my ObjectScript code. The main blocker was passing a Python list from a Python class method to a ObjectScript method. Sending the list by reference to the python method, populating it with the Insert() method, and returning the reference to the ObjectScript method resulted in an list with type %SYS.Python, a process that was straightforward but not efficient.
I explored an alternative method: converting a Python list to an ObjectScript list using JSON as the intermediary format. This approach appears to require less code and offers improved runtime performance.
Inside the python code:
list = ["a", "b", "c", "d"]
jsonExport = json.dumps(list)
Inside the ObjectScript code:
jsonExport = ##class(Example.Case).GetPythonList()
set list = ##class(%DynamicAbstractObject).%FromJSON(jsonExport)
Comments
You can also shorthand the ObjectScript call to %FromJSON() by using:
set list = [].%FromJSON(jsonExport)
or
set list = {}.%FromJSON(jsonExport)
When you set an ObjectScript variable equal to either [] (DynamicArray) or {} (DynamicObject), the variable becomes an instance of the respective dynamic entity class automatically, so it saves you having to type out the entire class reference.