I'm loading a string into a dictionary. json.loads()
fails because by default the strings use single quotes to wrap property names and values, although in some cases the value is wrapped in double quotes because it contains a single quote.
Here is a reproduceable example using Python3.8
>>> import json
>>> example = "{'msg': \"I'm a string\"}"
>>> json.loads(example.replace("'", '"'))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python3.8/json/__init__.py", line 357, in loads
return _default_decoder.decode(s)
File "/usr/local/lib/python3.8/json/decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/usr/local/lib/python3.8/json/decoder.py", line 353, in raw_decode
obj, end = self.scan_once(s, idx)
json.decoder.JSONDecodeError: Expecting ',' delimiter: line 1 column 12 (char 11)
Is there a better way to load a string into a dictionary? The json
module only works with double quotes and as that is not possible here (I have no control over string formatting), hence why I'm having to use the unreliable replace
.
My desired result is to have a dictionary like this:
{'msg': "I'm a string"}
Use ast.literal_eval()
Docs:
>>> import ast
>>> ast.literal_eval(example)
{'msg': "I'm a string"}