<p>下面是递归遍历dict结构的示例代码。对于本例,它将描述替换为描述的大写。在</p>
<pre><code>_DESC = "description"
_BASESYS = "base_system"
_SUBSYS = "sub_systems"
def uppercase_desc(system_info):
"""
Change a system object such that the description is in upper-case.
"""
if _BASESYS not in system_info:
return
subd = system_info[_BASESYS]
if _DESC in subd:
subd[_DESC] = subd[_DESC].upper()
if _SUBSYS not in subd:
return
for d in subd[_SUBSYS]:
uppercase_desc(d)
if __name__ == "__main__":
import json
with open("data.json", "rt") as f:
s = f.read()
system_info = json.loads(s)
uppercase_desc(system_info)
s = json.dumps(system_info, indent=4, sort_keys=True)
print(s)
</code></pre>
<p>上面的代码对字典进行了适当的修改。这是一个有点棘手,但并不坏,在你去做一个副本,并返回副本。这可能更好。在</p>
<p>这里唯一棘手的部分是代码默认使用<code>copy.deepcopy()</code>。因为我们不知道字典中可能有什么内容,并且我们想返回一个副本,所以我们可以对所有内容调用<code>copy.deepcopy()</code>;它将非常简单地工作,并对像<code>3</code>(值为3的整数对象)这样的简单对象执行正确的操作。在</p>
^{pr2}$
<p>另外,您发布的示例数据不是有效的JSON。我修改了它,在键的两边加上双引号,并用漂亮的缩进打印出来,使我的测试文件<code>data.json</code>。这里是:</p>
<pre><code>{
"base_system": {
"name": "root",
"description": "data dictionary",
"more_data": {},
"common_data": {},
"sub_systems": [
{
"base_system": {
"name": "another system",
"sub_systems": [
{
"base_system": {}
},
{
"base_system": {}
}
],
"description": "inherits from top level"
}
},
{
"base_system": {
"name": "one more system",
"sub_systems": [
{
"base_system": {
"more_data": {},
"other_data": {},
"name": "child system",
"description": "no kids here"
}
},
{
"base_system": {
"name": "kid system",
"description": "no children here"
}
}
],
"description": "inheriting again"
}
}
],
"other_data": {}
}
}
</code></pre>