| 1 | import json |
| 2 | |
| 3 | # Encode Schema into JSON |
| 4 | class SchemaEncoder(): |
| 5 | # encode schema to JSON string |
| 6 | def to_JSON(self, schema) -> str: |
| 7 | return json.dumps(self.encode(schema), indent=4) |
| 8 | |
| 9 | # encode schema as dict |
| 10 | def encode(self, schema) -> dict: |
| 11 | # Make sure schema is valid |
| 12 | schema.validate() |
| 13 | |
| 14 | dict = {'entities': [], 'relations': []} |
| 15 | |
| 16 | for e in schema.entities: |
| 17 | dict['entities'].append(self._encode_entity(e)) |
| 18 | |
| 19 | for r in schema.relations: |
| 20 | dict['relations'].append(self._encode_relation(r)) |
| 21 | |
| 22 | return dict |
| 23 | |
| 24 | # Dump Entity into a dict |
| 25 | # format: |
| 26 | # {'name': name, |
| 27 | # 'attributes': [ |
| 28 | # {'name': attr_name, |
| 29 | # 'type': attr_type, |
| 30 | # 'unique': attr_unique},... |
| 31 | # ] |
| 32 | # } |
| 33 | def _encode_entity(self, e): |
| 34 | dict = {'name': e.name, 'attributes': []} |
| 35 | |
| 36 | for attr in e.attributes: |
| 37 | dict['attributes'].append({'name': attr.name, 'type': attr.type.__name__, 'desc': attr.desc, 'unique': attr.unique, 'mandatory': attr.mandatory}) |
| 38 | |
| 39 | return dict |
| 40 | |
| 41 | # Dump Relation into dict |
| 42 | def _encode_relation(self, r): |
| 43 | return {'name': r.name, 'src': r.src.name, 'dest': r.dest.name} |