I have a very strange data file which I have no idea how to loop through the keys. Here is the file:
(The file is generated from an API server. No way to change the input)
{'client': <object at 0xc0>, 'store': {'name': 'test', 'number': 7, 'modified': '2020-09-11T00:32:56Z', 'id': '0833-f780'}, 're': re.compile('^(http://mysite.tesdt.com)/(.+)$')}
I am trying to extract 'number' from the data. But seems like there is no way. I have tried json.loads
, eval(data)
, or any other combinations to convert it to a native python dict. As you can see below, all these chunks of code did not work:
Try #1:
file = "file.json"
data = file.read()
parsed = json.loads(data)
print(data)
Error:
AttributeError: 'str' object has no attribute 'read'
Try #2:
with open("file.json", "r") as f:
data = f.read()
d = ast.literal_eval(data)
print(d)
Error:
{'client': <object at 0xc0>, 'store': {'name': 'test', 'number': 7, 'modified': '2020-09-11T00:32:56Z', 'id': '0833-f780'}, 're': re.compile('^(http://mysite.tesdt.com)/(.+)$')}
^
SyntaxError: invalid syntax
Try #3:
with open("file.json", "r") as f:
data = f.read()
data = data.replace("'", '"')
print(data)
js = json.loads(data)
print(js)
Error:
json.decoder.JSONDecodeError: Expecting value: line 1 column 12 (char 11)
Try #4:
with open("file.json", "r") as f:
data = f.read()
data = str(data)
print(json.dumps(data))
js = json.loads(data)
print(js)
Error:
json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)