这个问题有些复杂,没有典型的答案浮出水面。
我正在开发的工具的性质决定我们使用MongoDB来存储大约25个不同工具的“设置”。每个工具都有自己的设置模式,因此每个文档都不同,但它们都存储在同一个集合中,并在由json模式绘制的相同编辑页面上进行编辑。
不知道字典的模式,我很难弄清楚如何迭代和清理数据,特别是删除密码。
鉴于以下字典,并知道其他字典可能具有不同的模式,如何遍历字典中的每个项并创建一个副本,与任何key ==“password”的项不同?
所以:
{
"_enabled": true,
"instances": [
{
"isdefault": true,
"name": "dev",
"password": "abc123",
"url": "http://dev.example.com",
"user": "buffy"
},
{
"isdefault": false,
"name": "prod",
"password": "xxxxx",
"url": "http://prod.example.com",
"user": "spike"
},
{
"isdefault": false,
"name": "qa",
"password": "dasddf",
"url": "http://prod.example.com",
"user": "willow"
}
],
"label": "MyServers"
}
应该得到以下结果:
{
"_enabled": true,
"instances": [
{
"isdefault": true,
"name": "dev",
"url": "http://dev.example.com",
"user": "buffy"
},
{
"isdefault": false,
"name": "prod",
"url": "http://prod.example.com",
"user": "spike"
},
{
"isdefault": false,
"name": "qa",
"url": "http://prod.example.com",
"user": "willow"
}
],
"label": "MyServers"
}
对于原始字典中的每个子字典,如果它包含'password',则删除'subdict['password']'。
- Two-Bit Alchemist