【发布时间】:2014-09-04 03:13:53
【问题描述】:
我有一本这样的字典:
source = {
'Section 1' : {
'range' : [0, 200],
'template' : 'ID-LOA-XXX',
'nomenclature': True
},
'Section 2' : {
'range' : [201, 800],
'template' : 'ID-EPI-XXX',
'nomenclature': False,
'Subsection 1' : {
'range' : [0, 400],
'template' : 'ID-EPI-S1-XXX',
'nomenclature': False,
'Subsubsection 1' : {
'range' : [0, 400],
'template' : 'ID-EPI-S12-XXX',
'nomenclature': False
}
},
'Subsection 2' : {
'range' : [0, 400],
'template' : 'ID-EPI-S2-XXX',
'nomenclature': False
}
},
# etc.
}
从 JSON 文件加载。我想将其“展平”到以下字典:
target = {
'Section 1' : {
'range' : [0, 200],
'template' : 'ID-LOA-XXX',
'nomenclature': True,
'location' : './Section 1/'
},
'Section 2' : {
'range' : [201, 800],
'template' : 'ID-EPI-XXX',
'nomenclature': False,
'location' : './Section 2/'
},
'Subsection 1' : {
'range' : [0, 400],
'template' : 'ID-EPI-S1-XXX',
'nomenclature': False,
'location' : './Section 2/Subsection 1/'
},
'Subsubsection 1' : {
'range' : [0, 400],
'template' : 'ID-EPI-S12-XXX',
'nomenclature': False,
'location' : './Section 2/Subsection 1/Subsubsection 1'
},
'Subsection 2' : {
'range' : [0, 400],
'template' : 'ID-EPI-S2-XXX',
'nomenclature': False,
'location' : './Section 2/Subsection 2/'
},
# etc.
}
我也许能够更改原始 JSON 文件的生成方式,但我不想去那里。
word 中的 JSON 文件:每个部分至少包含三个键,可能包含其他键。那些其他键被解释为包含在当前节中的子节,每个都是具有相同属性的dict。这种模式原则上可以无限深地递归。
我还想执行一些断言:
- 是否存在所有必填字段(
'range'、'template'和'nomenclature') - 必填字段的值通过某些断言
到目前为止,我只设法进行了这些检查:
import json
key_requirements = {
"nomenclature": lambda x : isinstance(x, bool),
"template" : lambda x : isinstance(x, str) and "X" in x,
"range" : lambda x : isinstance(x, list) and len(x)==2 and all([isinstance(y,int) for y in x]) and x[1] > x[0]
}
def checkSection(section):
for key in section:
if key not in key_requirements:
checkSection(section[key])
elif not key_requirements[key]( section[key] ):
# error: assertion failed
pass
else:
# error: key not present
pass
for key in source # json.load(open(myJsonFile))
checkSection(data[key])
但目前,再多的咖啡也无法让我想出一种高效、优雅、pythonic 的方式来将所需的转换编织到这个方案中......
有什么建议或想法吗?
【问题讨论】:
标签: python json dictionary map flatten