I am trying to load a string (the actual program read this line from a file and it is a very large file that I can not manually modify) formatted as a dictionary.
I need to convert the string line into a json object so I can check value of specific key, e.g. myJson[Date] .
This is the script:
import json
mystring = "{'Date': 'Fri, 19 Apr 2019 03:58:04 GMT', 'Server': 'Apache/2.4.39', 'Accept-Ranges': 'bytes'}"
mystring = json.dumps(mystring)
myJson = json.loads(mystring)
print(str(myJson.keys()))
print(str(myJson))
I am getting this error:
AttributeError: 'str' object has no attribute 'keys'
I suspect that the mystring format is not conforming and that the single quotes should be double quotes? Given that I have a large data, and I can not simply replace single colons with double one using simple search/replace as single colons may be included in the values which I should not modify. If this is the cause of the problem, is there any way to replace the colons of the key/value pair only without touching the colons in the values? I am hoping that this is not the problem.
mystring = json.dumps(mystring)? Besides your string is not valid JSON (single quotes instead of double).mystringcome from? It looks like you took a perfectly good dict and converted it into a string. The correct course of action is most likely not to add more processing steps, but to remove an earlier, incorrect step.ast.literal_evalor a permissive JSON parser.json.dumpswill definitely not be part of the correct solution.mystringis not valid JSON to begin with — it needs double quotes to be json.strobject into a JSON string object. So when you deserialize it, it is going to be a string. As others have noted, your string doesn't actually contain valid JSON to begin with, but in any case, you almost certainly didn't mean tojson.dumps(mystring)first. That doesn't make any sense.