Skip to content

Commit 03ac71f

Browse files
author
zat
committed
add dataschema, create class from json and create json from class
1 parent 593ac84 commit 03ac71f

File tree

4 files changed

+35
-9
lines changed

4 files changed

+35
-9
lines changed

src/datamodel/Character.json

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
{
2+
"name": "",
3+
"age": int
4+
}
613 Bytes
Binary file not shown.

src/log_analyser/object/character.py

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,12 +4,17 @@
44
class Character(Object):
55

66
def __init__(self, **kwargs):
7-
super().__init__(**kwargs)
8-
7+
8+
data_schema = {"name": str,
9+
"age": int}
10+
11+
super().__init__(data_schema, **kwargs)
912

1013
def __print__(self):
1114
print(vars(self))
1215

13-
character = Character.from_json({"name": "ok", "test": "lol"})
16+
character = Character.from_json({"name": "ok", "age": 3})
17+
18+
character.__print__()
1419

15-
character.__print__()
20+
print(character.export_json())

src/log_analyser/object/object.py

Lines changed: 22 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,14 +2,31 @@
22

33

44
class Object:
5-
def __init__(self, **kwargs):
6-
for key, value in kwargs.items():
7-
setattr(self, key, value)
5+
def __init__(self, class_model, **kwargs):
6+
7+
self.from_json_ok = True
88

9+
for key, value in kwargs.items():
10+
if key in class_model:
11+
if type(value) == class_model[key]:
12+
setattr(self, key, value)
13+
else:
14+
print("type of key {} is invalid".format(key))
15+
self.from_json_ok = False
16+
else:
17+
print("key {} not find in dataschema".format(key))
18+
self.from_json_ok = False
19+
920
def export_json(self):
1021

11-
return json.dumps(self.__dict__)
22+
dict_class = self.__dict__
23+
dict_class.pop("from_json_ok")
24+
return json.dumps(dict_class)
1225

1326
@classmethod
1427
def from_json(self, data):
15-
return self(**data)
28+
object = self(**data)
29+
if object.from_json_ok:
30+
return object
31+
else:
32+
return None

0 commit comments

Comments
 (0)