Home > Net >  String with backslashes to dictionary
String with backslashes to dictionary

Time:12-22

I have the following string:

txt = "{\'legs_a\': 1,\'legs_b\': 0,\'score_a\': 304,\'score_b\': 334,\'turn\': B,\'i\': 2,\'z\': 19}"

When I print it, I see the below output in my console

{'legs_a': 1,'legs_b': 0,'score_a': 304,'score_b': 334,'turn': B,'i': 2,'z': 19}

I want to make a dictionary of the string by using ast.literal_eval()

import ast
d = ast.literal_eval(txt)

This yields the following error:

{ValueError}malformed node or string: <_ast.Name object at 0x7fb8b8ab4fa0>

Please explain what's going wrong? How can I make a dictionary from the string? Thanks

CodePudding user response:

B is an undefined variable or unquoted string.

try:

txt = "{\'legs_a\': 1,\'legs_b\': 0,\'score_a\': 304,\'score_b\': 334,\'turn\': \'B\',\'i\': 2,\'z\': 19}"
d = ast.literal_eval(txt)
print(d)

Output:

{'legs_a': 1, 'legs_b': 0, 'score_a': 304, 'score_b': 334, 'turn': 'B', 'i': 2, 'z': 19}

Note if you wanted to deserialze the JSON string using json.loads() function then you would need to replace single quotes with double quotes.

data = json.loads(txt.replace("'", '"'))
  • Related