我正在尝试从先前定义和创建的 JSON 模式开始在 Python 中生成一个新类。然后我想使用自动生成的类来读取 JSON 文件。我的问题是我设法使用“python_jsonschema_objects”或“marshmallow_jsonschema”从模式创建类,但是当我创建属于该类的对象时,python 不建议该类中的元素。(我想输入object.name,并且我希望python建议“名称”,因为它知道名称是对象的属性)。此外,这些工具创建的类在第一种情况下是“abc.class”,在第二种情况下是“类'marshmallow.schema.GeneratedSchema'”。我在这里留下一个代码示例:
from marshmallow import Schema, fields, post_load
from marshmallow_jsonschema import JSONSchema
from pprint import pprint
import json
class User(object):
def __init__(self, name, age):
self.name = name
self.age = age
def __repr__(self):
return f'I am {self.name} and my age is {self.age}'
class UserSchema(Schema):
name = fields.String()
age = fields.Integer()
@post_load
def make(self, data):
return User(data)
schema = UserSchema()
json_schema = JSONSchema()
print(json_schema.dump(schema))
with open(abs_path + "schema_test_file.json" , 'w') as outfile:
json.dump(json_schema.dump(schema), outfile)
with open(abs_path + "schema_test_file.json" ) as json_file:
data = json.load(json_file)
schema = UserSchema().from_dict(data) **class 'marshmallow.schema.GeneratedSchema'**
user = schema()
user.name = "Marco" **I would like here that python suggest name and age as properties of schema**
user.age = 14
我希望我已经足够清楚了。