由于听起来您的数据可能是动态的,并且您希望可以自由地在 JSON 对象中添加更多字段,而不反映模型中的相同更改,因此我还建议您查看一下typing.TypedDict https://docs.python.org/3/library/typing.html#typing.TypedDict相反dataclass
.
这是一个例子TypedDict
,它应该在 Python 3.7+ 中工作。由于 TypedDict 是3.8中引入 https://www.python.org/dev/peps/pep-0589/,我改为从typing_extensions https://pypi.org/project/typing-extensions/所以它与3.7代码兼容。
from __future__ import annotations
import json
from io import StringIO
from typing_extensions import TypedDict
class Account(TypedDict):
email: str
password: str
name: str
salary: int
json_data = StringIO("""{
"acc1":{
"email":"[email protected] /cdn-cgi/l/email-protection",
"password":"acc1",
"name":"ACC1",
"salary":1
},
"acc2":{
"email":"[email protected] /cdn-cgi/l/email-protection",
"password":"acc2",
"name":"ACC2",
"salary":2,
"someRandomKey": "string"
}
}
""")
data = json.load(json_data)
name_to_account: dict[str, Account] = data
acct = name_to_account['acc2']
# Your IDE should be able to offer auto-complete suggestions within the
# brackets, when you start typing or press 'Ctrl + Space' for example.
print(acct['someRandomKey'])
If you are开始使用数据类来建模数据,我建议检查 JSON 序列化库,例如数据类向导 https://dataclass-wizard.readthedocs.io/ (免责声明:我是创建者),它应该处理前面提到的 JSON 数据中的无关字段,以及嵌套数据类模型(如果您发现数据变得更加复杂)。
它还具有一个方便的工具,可用于从 JSON 数据生成数据类架构,例如,如果您想要在 JSON 文件中添加新字段(如上所述)时更新模型类,则该工具非常有用。