【发布时间】:2021-05-15 09:11:20
【问题描述】:
我正在尝试将配置从客户端传输到服务器。
- 配置包含一个
password密钥,我不能传输 - Config 包含几个简单的对象,它们只是键/值对(其中 value 是基本原语)
此代码有效:
class Empty:
pass
class Config:
def __init__(self):
# don't want to transmit this over the internet
self.secret = 'P@ssw0rd'
def create(self, foo):
self.foo = foo # property passed in
self.bar = f'Hello {foo}' # calculated property
# A couple of custom objects, but they are simple
# (only containing key/value pairs where value is basic primitive)
self.v = Empty()
self.v.a = 1
self.w = Empty()
self.w.b = 2
def export_json(self):
J = {}
for k, v in vars(self).items():
if k == 'secret':
continue
J[k] = vars(v) if isinstance(v, Empty) else v
return J
def construct_from_json(self, J_str):
J = json.loads(J_str)
for k, v in J.items():
if isinstance(v, dict):
_ = Empty()
for k_, v_ in v.items():
setattr(_, k_, v_)
v = _
setattr(self, k, v)
Test:
```python
c = Config()
c.create('123')
J = c.export_json()
print('Serialized:')
print(json.dumps(J, indent=4))
d = Config()
d.construct_from_json(J)
print('Reconstructed: w.b = ', d.w.b)
输出:
Serialized:
{
"foo": "123",
"bar": "Hello 123",
"v": {
"b": 2
},
"w": {
"b": 2
}
}
Reconstructed: w.b = 2
但是,是否有首选/pythonic 方式来执行此操作?
【问题讨论】:
-
你看过
pickle吗?
标签: python object json-serialization