Python ast.literal_eval on dictionary string not working (SyntaxError: invalid syntax)

半世苍凉 提交于 2019-12-06 14:34:03

问题


I am trying to process a dataset with JSON data. However, the data have been written on a file without being parsed. That means that a python dictionary is written in the file as a string instead of a JSON object as a string.

I've found a module (AST) that will do the job to convert the string to a dictionary again using the ast.literal_eval function.

However, I am getting a very strange error in some of the instances:

The code reads from a text file and apply the following to each line:

ast.literal_eval(line.rstrip())

It seems some of the characters are not ok with the AST module.

Need to recall as well that this is not happening with all the dataset, just with some instances.

Any ideas?

Many thanks in advance.


回答1:


Try exploring the json package. It is cleaner and more standard way of converting strings to dictionary

json.loads(inputStr) // Converts string -> dict
json.dumps(inputJson) // Converts dict -> string

Hope this helps. Cheers!



来源:https://stackoverflow.com/questions/42161202/python-ast-literal-eval-on-dictionary-string-not-working-syntaxerror-invalid-s

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!