使用理解为 Json 字典列表中的每个键添加前缀

Add a prefix to each key in Json dictionary list using comprehension

我希望为 JSON 中的每个键添加前缀,因此我的消息如下所示,带有 tmp. 前缀

[{'tmp.p.class': 'B', 'tmp.timestamp': '2020-08-07 09:00:00'}, {'tmp.p.class': 'A', 'tmp.timestamp': '2020-08-07 09:00:05'}]

import json      
x = [{'p.class': 'B', 'timestamp': '2020-08-07 09:00:00'}, {'p.class': 'A', 'timestamp': '2020-08-07 09:00:05'}]
data = json.dumps(x)

y = [{'tmp.'+k: v for k, v in d.items()} for d in data]
print(y)

Traceback (most recent call last): File "./prog.py", line 5, in File "./prog.py", line 5, in AttributeError: 'str' object has no attribute 'items'

您不需要将 python 对象序列化为字符串。可以直接对列表进行修改x.

y = [{"tmp." + k: v for k, v in d.items()} for d in x]