Reputation: 55
When I'm trying to parse a JSON dump, I get this attribute error
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'
Script:
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()
Upvotes: 0
Views: 625
Reputation: 1454
json.load - is used for files / objects json.loads - is used for the strings or array elements.
You may also think about creating the whole JSON in the form of HEREDOC formate at once and latter apply escaping on it - this way it become easier to validate JSON format.
Upvotes: 0
Reputation: 21243
Your code
header_final=json.dumps(finalJson,indent=4)
will give you string,
you have to use json.loads
to convert string to json.
Upvotes: 0
Reputation: 25329
json.dumps
returns a JSON formatted string, but json.load
expects to get file-like objects, not strings.
Solution: use json.loads
instead of json.load
in your code
Upvotes: 3