当前第2页 返回上一页
由于 json 语法规定 数组或对象之中的字符串必须使用双引号,不能使用单引号 (官网上有一段描述是 “A string is a sequence of zero or more Unicode characters, wrapped in double quotes, using backslash escapes” ),因此下面的转换是错误的:
1
2
3
4
5
6
7
8
9
10
11
12
13
>>> import json
>>> user_info =
"{'name' : 'john', 'gender' : 'male', 'age': 28}"
# 由于字符串使用单引号,会导致运行出错
>>> user_dict = json.loads(user_info)
Traceback (most recent call last):
File
"<stdin>"
, line 1, in <module>
File
"/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.py"
, line 339, in loads
return
_default_decoder.decode(s)
File
"/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py"
, line 364, in decode
obj,
end
= self.raw_decode(s, idx=_w(s, 0).
end
())
File
"/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py"
, line 380, in raw_decode
obj,
end
= self.scan_once(s, idx)
ValueError: Expecting property name: line 1 column 2 (char 1)
2、通过 eval
1
2
3
4
5
6
7
8
>>> user_info =
'{"name" : "john", "gender" : "male", "age": 28}'
>>> user_dict =
eval
(user_info)
>>> user_dict
{
'gender'
:
'male'
,
'age'
: 28,
'name'
:
'john'
}
>>> user_info =
"{'name' : 'john', 'gender' : 'male', 'age': 28}"
>>> user_dict =
eval
(user_info)
>>> user_dict
{
'gender'
:
'male'
,
'age'
: 28,
'name'
:
'john'
}
通过 eval 进行转换就不存在上面使用 json 进行转换的问题。但是,使用 eval 却存在安全性的问题,比如下面的例子:
1
2
3
4
5
6
7
# 让用户输入 `user_info`
>>> user_info = raw_input(
'input user info: '
)
# 输入 {
"name"
:
"john"
,
"gender"
:
"male"
,
"age"
: 28},没问题
>>> user_dict =
eval
(user_info)
# 输入 __import__(
'os'
).system(
'dir'
),user_dict 会列出当前的目录文件!
# 再输入一些删除命令,则可以把整个目录清空了!
>>> user_dict =
eval
(user_info)
3、通过 literal_eval
1
2
3
4
5
6
7
8
9
>>> import ast
>>> user =
'{"name" : "john", "gender" : "male", "age": 28}'
>>> user_dict = ast.literal_eval(user)
>>> user_dict
{
'gender'
:
'male'
,
'age'
: 28,
'name'
:
'john'
}
user_info =
"{'name' : 'john', 'gender' : 'male', 'age': 28}"
>>> user_dict = ast.literal_eval(user)
>>> user_dict
{
'gender'
:
'male'
,
'age'
: 28,
'name'
:
'john'
}
使用 ast.literal_eval 进行转换既不存在使用 json 进行转换的问题,也不存在使用 eval 进行转换的 安全性问题,因此推荐使用 ast.literal_eval。
以上就是如何将字符串转成字典的详细内容,更多文章请关注木庄网络博客 !!
返回前面的内容
相关阅读 >>
Python 如何使用xlrd实现读取合并单元格
Python 经典算法有哪些
关于Python 中引入导入与自定义模块以及外部文件的实例分享
Python 卸载模块的方法汇总
Python 和go语言有区别吗
Python 格式化输出%s和%d
Python 拷贝特定后缀名文件,并保留原始目录结构的实例
开启Python 取经之路-class-6(part 1)
linux6.5版本下如何安装Python
Python 使用四种方法实现获取当前页面内所有链接的对比分析
更多相关阅读请进入《Python 》频道 >>
¥69.8元 人民邮电出版社
python入门书籍,非常畅销,超高好评,python官方公认好书。
转载请注明出处:木庄网络博客 » 如何将字符串转成字典