From b4758fb52b933c0eedc2f314ec9b5ea3fc3c8e29 Mon Sep 17 00:00:00 2001 From: Daniel Mach Date: Mon, 8 Sep 2025 09:53:47 +0200 Subject: [PATCH] Add BaseModel.from_string() and BaseModel.to_string() methods --- osc/util/models.py | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/osc/util/models.py b/osc/util/models.py index 6f18faef..e87fb238 100644 --- a/osc/util/models.py +++ b/osc/util/models.py @@ -485,6 +485,26 @@ class BaseModel(metaclass=ModelMeta): # we prefer key ordering according to the fields in the model json.dump(self.dict(), f, sort_keys=False, indent=4) + @classmethod + def from_string(cls, text: str) -> "Self": + """ + Load model from json string. + """ + import json + + data = json.loads(text) + obj = cls(**data) + return obj + + def to_string(self) -> str: + """ + Dump model to a json string. + """ + import json + + result = json.dumps(self.dict(), sort_keys=False, indent=4) + return result + def do_snapshot(self): """ Save ``self.dict()`` result as a new starting point for detecting changes in the object data.