Python几种常见的字符串转换字典方法

在日常使用Python的过程中,有时会遇到这种需求。将一个字符串转换为字典格式。

举例

str = "{'id': 123, 'name': 'Tom', 'age': 12}"
print(type(str))

# 运行结果

<class 'str'>

下面介绍几种将字符串转为字典的方法并介绍相关注意事项

目录

1.使用json

2.使用eval

3.使用literal_eval


1.使用json

第一种情况

import json

str = '{"id": 123, "name": "Tom", "age": 12}'
print(type(str))
str_c = json.loads(str)
print(type(str_c))

# 运行结果

<class 'str'>
<class 'dict'>

第二种情况

import json

str = "{'id': 123, 'name': 'Tom', 'age': 12}"
print(type(str))
str_c = json.loads(str)
print(type(str_c))

# 运行结果

json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)

可以看出第一种情况运行正常,格式转换成功,而第二种却报错。

解释:其官网上有一段描述是 “A string is a sequence of zero or more Unicode characters, wrapped in double quotes, using backslash escapes” ,因此 json 语法规定 数组或对象之中的字符串必须使用双引号,不能使用单引号。

2.使用eval

str = "{'id': 123, 'name': 'Tom', 'age': 12}"
print(type(str))
str_c = eval(str)
print(type(str_c))

# 运行结果

<class 'str'>
<class 'dict'>

注意:使用eval存在安全隐患。

3.使用literal_eval

import ast

str = "{'id': 123, 'name': 'Tom', 'age': 12}"
print(type(str))
str_c = ast.literal_eval(str)
print(type(str_c))

# 运行结果

<class 'str'>
<class 'dict'>

注意:当键值有空值时不能使用literal_eval。

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值