如何将 json 文件转换为 python 类?

2024-02-25

考虑这个名为h.json我想将其转换为 python 数据类。

{
    "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
    }

}

我可以使用替代构造函数来获取每个帐户,例如:

import json
from dataclasses import dataclass

@dataclass
class Account(object):
    email:str
    password:str
    name:str
    salary:int
    
    @classmethod
    def from_json(cls, json_key):
        file = json.load(open("h.json"))
        return cls(**file[json_key])

但这仅限于数据类中定义的参数(电子邮件、姓名等)。

如果我要修改 json 以包含其他内容(例如年龄)怎么办? 该脚本最终会返回一个TypeError, 具体来说TypeError: __init__() got an unexpected keyword argument 'age'.

有没有办法根据dict(json对象)的键动态调整类属性,这样我就不必每次向json添加新键时都添加属性?


由于听起来您的数据可能是动态的,并且您希望可以自由地在 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 文件中添加新字段(如上所述)时更新模型类,则该工具非常有用。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何将 json 文件转换为 python 类? 的相关文章

随机推荐