JSON import
This example illustrates importing a SysML v2 model from a JSON file by deserializing
it. The main function of interest is json.loads, which takes the JSON text and
the URI of the Document the model is deserialized into. That URI does not have
to exist on the local file system; it is what relative references inside the JSON are
resolved against. The deserialized model can then be used as if it had been loaded from
a .sysml file.
Concepts used
A
DeserializedModelis the first of the two valuesjson.loadsreturns, and itsdocumentholds the model that was read from the JSON.The
syside.jsonmodule for reading SysML v2 JSON back into a model.walk_ownership_treeis a function that prints out elements in a model in a tree-like format. In this example it is used to show that the model has been successfully deserialized from JSON format.
Example script
import pathlib
import syside
EXAMPLE_DIR = pathlib.Path(__file__).parent
MODEL_FILE_PATH = EXAMPLE_DIR / "example_model_3.sysml"
# The deserialized model will be stored in a document with MODEL_PATH path.
# The MODEL_PATH does not necessarily need to exist on the local file system.
# as_uri() forms a valid file URL from Windows paths too.
MODEL_PATH = MODEL_FILE_PATH.as_uri()
def walk_ownership_tree(element: syside.Element, level: int = 0) -> None:
"""
Prints out all elements in a model in a tree-like format, where
child elements appear indented under their parent elements. For
example:
Parent
Child1
Child2
Grandchild
Args:
element: The model element to start printing from
level: How many levels to indent (increases for nested elements)
"""
if element.name is not None:
print(" " * level, element.name)
else:
print(" " * level, "anonymous element")
# Recursively call walk_ownership_tree() for each owned element
# (child element).
element.owned_elements.for_each(
lambda owned_element: walk_ownership_tree(owned_element, level + 1)
)
def main() -> None:
with open(EXAMPLE_DIR / "example_json.json", "r") as f:
json_import = f.read()
deserialized_model, _ = syside.json.loads(json_import, MODEL_PATH)
walk_ownership_tree(deserialized_model.document.root_node)
if __name__ == "__main__":
main()
Output
anonymous element
JSON Export Example
Electrical
Mechanical
Automobile
Drive Train
Chassis
Download
Download this example as json_loads.zip.