Skip to content

Commit b4758fb

Browse files
committed
Add BaseModel.from_string() and BaseModel.to_string() methods
1 parent 8d5546e commit b4758fb

File tree

1 file changed

+20
-0
lines changed

1 file changed

+20
-0
lines changed

osc/util/models.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -485,6 +485,26 @@ def to_file(self, path: str):
485485
# we prefer key ordering according to the fields in the model
486486
json.dump(self.dict(), f, sort_keys=False, indent=4)
487487

488+
@classmethod
489+
def from_string(cls, text: str) -> "Self":
490+
"""
491+
Load model from json string.
492+
"""
493+
import json
494+
495+
data = json.loads(text)
496+
obj = cls(**data)
497+
return obj
498+
499+
def to_string(self) -> str:
500+
"""
501+
Dump model to a json string.
502+
"""
503+
import json
504+
505+
result = json.dumps(self.dict(), sort_keys=False, indent=4)
506+
return result
507+
488508
def do_snapshot(self):
489509
"""
490510
Save ``self.dict()`` result as a new starting point for detecting changes in the object data.

0 commit comments

Comments
 (0)