当我试图解析JSON转储时,会得到以下属性错误
Traceback (most recent call last):
File "Security_Header_Collector.py", line 120, in <module>
process(sys.argv[-1])
File "Security_Header_Collector.py", line 67, in process
server_details = json.load(header_final)
File "/usr/lib/python2.7/json/__init__.py", line 274, in load
return loads(fp.read(),
AttributeError: 'str' object has no attribute 'read'
剧本:
finalJson[App[0]] = headerJson
header_final=json.dumps(finalJson,indent=4)
#print header_final
#json_data=open(header_final)
server_details = json.load(header_final)
with open("Out.txt",'wb') as f :
for appid, headers in server_details.iteritems():
htypes = [h for h in headers if h in (
'content-security-policy', 'x-frame-options',
'strict-transport-security', 'x-content-type-options',
'x-xss-protection')]
headers='{},{}'.format(appid, ','.join(htypes))
f.write(headers+'\n')
f.close()
发布于 2015-05-28 23:15:31
json.dumps
返回一个JSON格式的字符串,但是json.load
希望得到类似文件的对象,而不是字符串。
解决方案:在代码中使用json.loads
而不是json.load
发布于 2015-05-28 23:16:47
你的代码
header_final=json.dumps(finalJson,indent=4)
会给你绳子,
您必须使用json.loads
将字符串转换为json。
发布于 2015-05-29 00:50:53
json.load -用于文件/对象json.loads -用于字符串或数组元素。
您还可以考虑立即以HEREDOC formate的形式创建整个JSON,而后者则对其应用转义--这样就可以更容易地验证JSON格式。
https://stackoverflow.com/questions/30523307
复制相似问题