配置保管员
现在又有一份文件等着你交接:一位同事要接手一个小型看板配置,但这份记录还不够稳定。字段里有多余空格,列表里混着空白和重复项,同一个意思还出现了不一致的写法。要是现在交出去,接手的人第一件事不是继续工作,而是先猜哪一个值才算正式版本。
你的任务就是把这份 JSON 风格配置整理成一份清楚、稳定、可读的记录。做完以后,下一位维护者应该能直接看懂要保留什么、启用什么、通知谁,而不用再回头问你这份配置到底该怎么解释。
先看一个更小的动作:把配置里的列表项目收干净
先别急着处理整份配置。先看一个更小的玩具例子,感受“列表项目先清理,再放回结构里”这个动作。
config = {
"theme": " twilight ",
"tools": [" charts ", "", "Charts", " alerts "]
}
clean_theme = config["theme"].strip().lower()
clean_tools = []
for tool in config["tools"]:
clean_tool = tool.strip().lower()
if clean_tool != "" and clean_tool not in clean_tools:
clean_tools.append(clean_tool)
print(clean_theme)
print(clean_tools)
这个例子没有处理完整文件,只是在示范今天的一种关键手感:先把结构里的脏字符串和重复项收好,整份配置才会变得可靠。
今天要交付什么:把 dashboard_config.json 整理成可读的配置记录
脚本已经读取了 dashboard_config.json,并把原始结果放进 raw_config。你要补完脚本,把关键字段、列表项目和嵌套字典收整齐,最后交出 final_config 和 config_summary。
完成 clean_config_list(items)。遍历每个 item,用 strip().lower() 清理它,跳过空白结果,再只保留第一次出现的清理后内容。
从 raw_config 里读出 workspace_name、owner 和 theme。前两个只需要 strip(),而 theme 还要再变成小写,让配置值更稳定。
用 clean_config_list(...) 清理 features、notification_emails 和 dashboard 里的 sidebar_links。同时把 dashboard["homepage"] 清理成稳定的小写字符串。
用清理后的变量组装 final_config,保留嵌套的 dashboard 结构。然后用 config_summary 对比原始列表数量和最终保留数量,让接手的人一眼看出这份配置已经被整理过。
同一个意思写了很多种、空白项和重复项混在里面、嵌套结构也不够整齐。你的工作不是扩写功能,而是把它收成一份谁拿到都看得懂的记录。
参考答案点击展开点击收起
import json
ASSET_FILENAME = "dashboard_config.json"
with open(ASSET_FILENAME, "r", encoding="utf-8") as file:
raw_config = json.load(file)
print("Raw config:", raw_config)
def clean_config_list(items):
cleaned_items = []
for item in items:
clean_item = item.strip().lower()
if clean_item != "" and clean_item not in cleaned_items:
cleaned_items.append(clean_item)
return cleaned_items
clean_workspace_name = raw_config["workspace_name"].strip()
clean_owner = raw_config["owner"].strip()
clean_theme = raw_config["theme"].strip().lower()
clean_features = clean_config_list(raw_config["features"])
clean_notification_emails = clean_config_list(raw_config["notification_emails"])
clean_homepage = raw_config["dashboard"]["homepage"].strip().lower()
clean_sidebar_links = clean_config_list(raw_config["dashboard"]["sidebar_links"])
final_config = {
"workspace_name": clean_workspace_name,
"owner": clean_owner,
"theme": clean_theme,
"features": clean_features,
"notification_emails": clean_notification_emails,
"dashboard": {
"homepage": clean_homepage,
"sidebar_links": clean_sidebar_links,
},
}
config_summary = {
"raw_feature_count": len(raw_config["features"]),
"kept_feature_count": len(clean_features),
"raw_email_count": len(raw_config["notification_emails"]),
"kept_email_count": len(clean_notification_emails),
"raw_sidebar_link_count": len(raw_config["dashboard"]["sidebar_links"]),
"kept_sidebar_link_count": len(clean_sidebar_links),
}
print("Final config:", final_config)
print("Config summary:", config_summary)高级技巧想更进一步?点击展开点击收起
这节课最重要的感受是:配置文件并不神秘,它也是一份要交给别人继续使用的结构化记录。
只要你会清理字符串、整理列表、重组字典,就已经能把一份原本交不出去的小配置,收成稳定的交接结果。