<p>如果您知道每个数据的结构(也就是说,在数组/字典的深度中应该有“password”键),这就很简单了。您只需在列表项和字典中循环查找“password”键。在</p>
<p>如果每个设置字典的结构都是不可预测的,那么你就必须想出一个解决方案。在这种情况下,我所做的就是将我的JSON转储到一个字符串中,使用regex删除/隔离我感兴趣的数据,然后将字符串加载回结构化JSON。在</p>
<p>像这样:</p>
<p>导入json,re</p>
<pre><code>raw_data = """{
"_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"
}"""
# I load and then dump my raw_data just to iron out any inconsistencies
# in formatting before applying regex. i.e., inconsistent use of " instead of '
structured_data = json.loads(raw_data)
dumped_data = json.dumps(structured_data)
scrubbed = re.sub(r'"password": ".*?",', '', dumped_data)
structured_scrubbed = json.loads(scrubbed)
</code></pre>
<p>结果:</p>
^{pr2}$