0

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()

3 Answers 3

3

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

Sign up to request clarification or add additional context in comments.

Comments

0

Your code

header_final=json.dumps(finalJson,indent=4)

will give you string,

you have to use json.loads to convert string to json.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.