Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
从python中的JSON文件创建对象(使用类方法)?_Python_Json_Class Method - Fatal编程技术网

从python中的JSON文件创建对象(使用类方法)?

从python中的JSON文件创建对象(使用类方法)?,python,json,class-method,Python,Json,Class Method,我想创建一个classmethod,它接受一个JSON(字典)字符串,并创建一个调用它的类的实例。 例如,如果我有一个类Person继承自一个类Jsonable,带有年龄和姓名: class Person(Jsonable): def __init__(self, name, age): self.name = name self.age = age class Jsonable: @classmethod def from_json(js

我想创建一个classmethod,它接受一个JSON(字典)字符串,并创建一个调用它的类的实例。 例如,如果我有一个类
Person
继承自一个类
Jsonable
,带有年龄和姓名:

class Person(Jsonable):
    def __init__(self, name, age):
        self.name = name
        self.age = age
class Jsonable:
    @classmethod
    def from_json(json_string):
        # do the magic here

如果我有一个JSON字符串
string=“{'name':'John','age':21}”
当我说
person1=Person.from_JSON(string)
时,我想创建一个名为John,年龄为21岁的person1。我还必须以某种方式保留类名,这样当我调用例如
Car.from_json(string)
时,它会引发一个TypeError

它假设在JSON字符串中有一个包含目标类名的key类

import json

class Jsonable(object):
    @classmethod
    def from_json(cls, json_string):
        attributes = json.loads(json_string)
        if not isinstance(attributes, dict) or attributes.pop('__class') != cls.__name__:
            raise ValueError
        return cls(**attributes)

但是,假设我在JSO中有以下方法:
def to_json(self,indent=4):返回json.dumps(self.\u dict,indent)
,它返回一个字典,其中属性作为键,值作为dict值。我想在from_json方法中使用这个字符串作为参数,它没有类键。我担心它不会包含任何类似类名的内容,所以你需要自己把它放在那里。是的,我想我找到了。不管怎样,我都成功了!:)谢谢