Python 如何将字符串转为字典
在工作中遇到一个小问题,需要将一个 python
的字符串转为字典,比如字符串:
user_info = '{"name" : "john", "gender" : "male", "age": 28}'
我们想把它转为下面的字典:
user_dict = {"name" : "john", "gender" : "male", "age": 28}
有以下几种方法:
1、通过 json 来转换
>>> import json
>>> user_info= '{"name" : "john", "gender" : "male", "age": 28}'
>>> user_dict = json.loads(user_info)
>>> user_dict
{u'gender': u'male', u'age': 28, u'name': u'john'}
但是使用 json
进行转换存在一个潜在的问题。
由于 json
语法规定 数组或对象之中的字符串必须使用双引号,不能使用单引号 (官网上有一段描述是 “A string is a sequence of zero or more Unicode characters, wrapped in double quotes, using backslash escapes” ),因此下面的转换是错误的:
>>> 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
>>> 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
却存在安全性的问题
,比如下面的例子:
# 让用户输入 `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)
eval转换时如果遇到null值会报错:NameError: name ‘null’ is not defined,解决方法:eval(user_info)改为json.loads(user_info)
3、通过 literal_eval
>>> 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 如何将字符串转为字典的更多相关文章
- 002、Python中json字符串与字典转换
1.测试用例文件TestCase.xlsx 2.编写Python文件进行读取 #!/usr/bin/env python # -*- coding:utf-8 -*- import time impo ...
- Python字符串转为字典方法大全
方法一: 通过内置函数eval str_info = '{"name": "test", "age": 18}' dict_info = e ...
- python一(字符串,字典)
list操作 name = ['小王','小米','小张','王强','张三','李四'] name.append('黄霑')#添加元素在最后一个 name.insert(,'王五')#指定下标插入元 ...
- python中的字符串 列表 字典
字符串 一个有序的字符集合 不可变 1,可以使用for in语句进行迭代循环,返回元素 2,in类是于str.find()方法但是是返回布尔结果 str.find()返回 ...
- python中 将字符串和字典的相互转换
1.首先引入json模块 # 引入json模块 import json 2.转换 #JSON到字典转化: dictinfo = json.loads(json_str) # 输出dict类型 字典到J ...
- python 一行代码字符串转字典方法
b = 'bid=Qzw9cKnyESM; ll="108288"; __yadk_uid=4YChvgeANLBEh4iV00n1tc0HQ8zpmSl1; __utmc=301 ...
- python json格式字符串转换为字典格式
不废话,看代码 #_*_ coding:utf- _*_ import os import json course=open('C:\\Users\\ly199\\Desktop\\list.txt' ...
- python 元组中元组转为字典
#create a tuple tuplex = ((, , "r")) print(dict((y, x) for x, y in tuplex))
- python 将类属性转为字典
class dictObj(object): def __init__(self): self.x = 'red' self.y = 'Yellow' self.z = 'Green' def do_ ...
随机推荐
- CF961D Pair Of Lines
题目描述 You are given n n n points on Cartesian plane. Every point is a lattice point (i. e. both of it ...
- P1483 序列变换
题目描述 给定一个由n个整数构成的序列,你需要对它进行如下操作: 操作1:输入格式“1 x y”,表示把所有a[kx](k为正整数,kx<=n)都加上y. 操作2:输入格式“2 j”,表示输出a ...
- POJ.3624 Charm Bracelet(DP 01背包)
POJ.3624 Charm Bracelet(DP 01背包) 题意分析 裸01背包 代码总览 #include <iostream> #include <cstdio> # ...
- printf函数用法小记
By francis_hao Aug 26,2017 C语言中printf函数是一个比较常用的函数,但是常用并不代表完全了解,本文翻译了printf的man手册,介绍了其全部功能(不包括ma ...
- Google新出品的数据格式:Protocol Buffer
转:http://blog.csdn.net/carson_ho/article/details/70037693
- Moodle简介
Moodle简介 一.概述 Moodle是Modular Object-Oriented Dynamic Learning Environment(模块化面向对象动态学习环境)的简称,中文译名为魔灯, ...
- beego入门小坑
刚接触beego,按照官网的文档操作,始终发现在orm操作数据的时候提示表不存在,数据库连接设置都没问题 "0 Error 1146: Table 'beego.archives' does ...
- Spring filter和拦截器(Interceptor)的区别和执行顺序
转载自:http://listenup.iteye.com/blog/1559553 1.Filter过滤器只过滤jsp文件不过滤action请求解决方案 解决办法:在web.xml中将filter的 ...
- Python爬虫学习笔记之极限滑动验证码的识别
代码: import time from io import BytesIO from PIL import Image from selenium import webdriver from sel ...
- 关于MyBatis一些小错误,元素内容必须由格式正确的字符数据或标记组成.
今天在Mapper.xml文件写查询语句报了个奇怪的错误 Caused by: org.apache.ibatis.builder.BuilderException: Error creating d ...