简体   繁体   中英

python eval error with converting string to dict

i am working with python and when i do eval on a string to get a dictionary it shows me the error "SyntaxError: invalid syntax" the string is received over a socket connection and it contains a dictionary. i need to get back the original dictionary

Exact error is below

File "<string>", line 1 
##here goes my long string received over socket
                                   ^
SyntaxError: invalid syntax

I have no idea whats going on in this. I know i can use pickle or json to send data but thats not the req at the moment

First, never use eval unless you have a very specific use case which requires it: it poses security risks. Instead, use ast.literal_eval .

Second, I cannot reproduce your error:

import ast

mystr = "{'a': 1, 'b': 2, 'c': 3, 'd': 4}"

ast.literal_eval(mystr)        # {'a': 1, 'b': 2, 'c': 3, 'd': 4}
type(ast.literal_eval(mystr))  # dict

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM