需要在 Python 中将 JSON 重新组织成新的结构。
例如:
{
'a' : 1,
'b' : 1,
'd' : {'d1' : '1', 'd2' : 2},
'm' : [
{'x' : 6, 'y' : 5, 'z' : {'foo' : 'foo1', 'bar' : 'bar1'} },
{'x' : 8, 'y' : 8, 'z' : {'foo' : 'foo2', 'bar' : 'bar2'} }
]
}
至
{
'new_a' : 1,
'new_d' : {'new_d1' : '1', 'new_d2' : 2},
'new_m' : [
{'new_x' : 6, 'new_z' : {'new_foo' : 'foo1', new_'bar : 'bar1'} },
{'new_x' : 8, 'new_z' : {'new_foo' : 'foo2', 'new_bar : 'bar2'} }
]
}
有一种旧JSON的新形式的想法
有没有更优雅的方法来做到这一点?
import json
new_data = {}
new_data['new_a'] = old_data['a']
new_data['new_d'] = {}
new_data['new_d']['new_d1'] = old_data['d']['d1']
new_data['new_d']['new_d2'] = old_data['d']['d2']
new_data['new_m'] = {}
new_m = []
for m in old_data:
new_m.append({'new_x' : m['x'], 'new_z' : {'new_foo' ....