>>> help(ast.literal_eval)
Help on function literal_eval in module ast:
literal_eval(node_or_string)
Safely evaluate an expression node or a string containing a Python
expression. The string or node provided may only consist of the following
Python literal structures: strings, numbers, tuples, lists, dicts, booleans,
and None.
例如:
>>> eval("shutil.rmtree('mongo')")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 1, in <module>
File "/opt/Python-2.6.1/lib/python2.6/shutil.py", line 208, in rmtree
onerror(os.listdir, path, sys.exc_info())
File "/opt/Python-2.6.1/lib/python2.6/shutil.py", line 206, in rmtree
names = os.listdir(path)
OSError: [Errno 2] No such file or directory: 'mongo'
>>> ast.literal_eval("shutil.rmtree('mongo')")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/opt/Python-2.6.1/lib/python2.6/ast.py", line 68, in literal_eval
return _convert(node_or_string)
File "/opt/Python-2.6.1/lib/python2.6/ast.py", line 67, in _convert
raise ValueError('malformed string')
ValueError: malformed string
>>> import json
>>> h = '{"foo":"bar", "foo2":"bar2"}'
>>> type(h)
<type 'str'>
>>> d = json.loads(h)
>>> d
{u'foo': u'bar', u'foo2': u'bar2'}
>>> type(d)
<type 'dict'>
94
string = "{'server1':'value','server2':'value'}"
#Now removing { and }
s = string.replace("{" ,"")
finalstring = s.replace("}" , "")
#Splitting the string based on , we get key value pairs
list = finalstring.split(",")
dictionary ={}
for i in list:
#Get Key Value pairs separately to store in dictionary
keyvalue = i.split(":")
#Replacing the single quotes in the leading.
m= keyvalue[0].strip('\'')
m = m.replace("\"", "")
dictionary[m] = keyvalue[1].strip('"\'')
print dictionary
11 回答
如果你不能使用Python 2.6,你可以使用简单的safeeval implmentntation,如http://code.activestate.com/recipes/364469/
它背负着Python编译器,因此您不必自己完成所有的工作 .
以OP为例:
我们可以使用Yaml来处理字符串中的这种非标准json:
如果字符串总是可以信任的话,你可以使用
eval
(或者按照建议使用literal_eval
;无论字符串是什么,它都是安全的 . )否则你需要一个解析器 . 如果JSON解析器(例如simplejson)只存储符合JSON方案的内容,则它将起作用 .使用
json
.ast
库消耗大量内存并且速度较慢 . 我有一个需要读取156Mb文本文件的进程 .Ast
转换字典json
延迟5分钟,内存减少60%!你可以试试这个 .
从Python 2.6开始,您可以使用内置的ast.literal_eval:
这比使用
eval
更安全 . 正如自己的文档所说:例如:
http://docs.python.org/2/library/json.html
JSON可以解决这个问题,虽然它的解码器需要围绕键和值的双引号 . 如果你不介意替换黑客......
请注意,如果您将单引号作为键或值的一部分,则由于不正确的字符替换而失败 . 只有在您对eval解决方案有强烈厌恶的情况下,才建议使用此解决方案 .
更多关于json单引号:jQuery single quote in JSON response
使用
json.loads
:没有使用任何库:
注意:由于它具有硬编码
split("'")
仅适用于数据为"single quoted"的字符串 .总结一下:
结果:
结论:更喜欢 json.loads