I have a string in the following form:
testline = "{""key1"": ""value1"", ""key2"": {""value2-subkey1"": ""value2-subvalue2""}}"
I would like to replace the double-double quotes with a single-double quote (“) and strip the initial and final double quote to finish with a dictionary.
So far, I’ve got something like this, which is very much not doing what I want.
import ast
# testline = testline.strip(")
testline = testline.replace('""', '"')
testlinedict = ast.literal_eval(testline)
This so far yields ValueError: malformed string
I want the final result to be:
testlinedict = {"key1": "value1", "key2": {"value2-subkey1": "value2-subvalue2"}}
The problem is that the double quotes are actually interpreted by Python, but not in the way you expected:
This is because in Python, like in C, several string literals following each other are interpreted as one large string, so
"abc""def" == "abcdef".If you define
testdatacorrectly, your solution works:Or, in case the first and last quote are actually part of the string: