如注释中所述,它
from是一个Python关键字,因此您不能将其用作变量名或属性名。因此,您需要使用备用名称,并在读取或写入JSON数据时进行转换。
要进行输出转换,您可以为提供新的编码器
json.dumps;您可以通过重写
ExchangeRates.json方法来做到这一点。要进行输入转换,请覆盖
ExchangeRates.from_json。
在这两种情况下,策略都是相似的:我们创建字典的副本(因此我们不会对原始字典进行变异),然后创建具有所需名称和值的新键,然后删除旧键。
这是一个在Python 2.6和3.6上测试过的快速演示:
import jsonclass PropertyEquality(object): def __eq__(self, other): return (isinstance(other, self.__class__) and self.__dict__ == other.__dict__) def __ne__(self, other): return not self.__eq__(other) def __repr__(self): return '%s(%s)' % (self.__class__.__name__, ', '.join(['%s=%s' % (k, v) for (k, v) in self.__dict__.items()]))class JsonAware(PropertyEquality): def json(self): return json.dumps(self, cls=GenericEnprer) @classmethod def from_json(cls, json): return cls(**json)class ExchangeRatesEnprer(json.JSONEnprer): def default(self, obj): d = obj.__dict__.copy() d['from'] = d['frm'] del d['frm'] return dclass ExchangeRates(JsonAware): def __init__(self, frm, to, rate): self.frm = frm self.to = to self.rate = rate def json(self): return json.dumps(self, cls=ExchangeRatesEnprer) @classmethod def from_json(cls, json): d = json.copy() d['frm'] = d['from'] del d['from'] return cls(**d)# Testa = ExchangeRates('a', 'b', 1.23)print(a.json())jdict = {"from": "z", "to": "y", "rate": 4.56, }b = ExchangeRates.from_json(jdict)print(b.json())典型输出
{"from": "a", "to": "b", "rate": 1.23}{"from": "z", "to": "y", "rate": 4.56}


