问题描述
我有一个 json 输出文件,我正在尝试使用 sha256 加密方法加密其中的 key(name) 值。在 dict 列表中出现两次名称,但每次我写的时候,变化都会反映一次。谁能告诉我哪里不见了?
Json structure:
Output.json
{
"site": [
{
"name": "google","description": "Hi I am google"
},{
"name": "microsoft","description": "Hi,I am microsoft"
}
],"veg": [
{
"status": "ok","slot": null
},{
"status": "ok"
}
]
}
代码:
import hashlib
import json
class test():
def __init__(self):
def encrypt(self):
with open("Output.json","r+") as json_file:
res = json.load(json_file)
for i in res['site']:
for key,val in i.iteritems():
if 'name' in key:
hs = hashlib.sha256(val.encode('utf-8')).hexdigest()
res['site'][0]['name'] = hs
json_file.seek(0)
json_file.write(json.dumps(res,indent=4))
json_file.truncate()
当前输出.json
{
"site": [
{
"name": "bbdefa2950f49882f295b1285d4fa9dec45fc4144bfb07ee6acc68762d12c2e3",{
"status": "ok"
}
]
}
解决方法
我认为您的问题出在这一行:
res['site'][0]['name'] = hs
您总是在更改 name
列表中第一个地图的 site
字段。我想你希望是这样的:
i['name'] = hs
以便您更新当前正在处理的地图(由 i
指向)。
不是迭代字典中的每个项目,您可以利用字典是为通过键查找值而制作的事实,并执行以下操作:
if 'name' in i:
val = i['name']
hs = hashlib.sha256(val.encode('utf-8')).hexdigest()
i['name'] = hs
json_file.seek(0)
json_file.write(json.dumps(res,indent=4))
json_file.truncate()
而不是这个:
for key,val in i.iteritems():
if 'name' in key:
...
另外,iteritems()
应该是 items()
,if 'name' in key
应该是 if key == 'name'
,因为 key
是一个字符串。实际上,您将匹配具有包含子字符串“name”的键名的任何条目。
更新:我注意到您正在多次写入整个文件,对于您加密的每个 name
条目一次。即使没有这个,我还是建议您打开文件两次……一次用于读取,一次用于写入。这比打开文件进行读取和写入以及必须查找和截断更可取。因此,以下是我在完整版代码中建议的所有更改以及其他一些调整:
import hashlib
import json
class Test:
def encrypt(self,infile,outfile=None):
if outfile is None:
outfile = infile
with open(infile) as json_file:
res = json.load(json_file)
for i in res['site']:
if 'name' in i:
i['name'] = hashlib.sha256(i['name'].encode('utf-8')).hexdigest()
with open(outfile,"w") as json_file:
json.dump(res,json_file,indent=4)
Test().encrypt("/tmp/input.json","/tmp/output.json")
# Test().encrypt("/tmp/Output.json") # <- this form will read and write to the same file
结果文件内容:
{
"site": [
{
"name": "bbdefa2950f49882f295b1285d4fa9dec45fc4144bfb07ee6acc68762d12c2e3","description": "Hi I am google"
},{
"name": "9fbf261b62c1d7c00db73afb81dd97fdf20b3442e36e338cb9359b856a03bdc8","description": "Hi,I am microsoft"
}
],"veg": [
{
"status": "ok","slot": null
},{
"status": "ok"
}
]
}