Python字符串str和json格式相互转换
作者:依然砥砺前行 时间:2023-01-21 03:26:25
前言:
str
转换为json
格式,前提一定需要保证这个str的格式和json是一致的,即左边最外层是大括号,右边的最外层是大括号。如果不一致,推荐用正则进行拆分至和json格式一致
1. 通过json.loads进行转换
import json
str = '{"name": "御姐", "age": 18}'
j = json.loads(str)
print(j)
print(type(j))
json
中内部数据需要用双引号来包围,不能使用单引号
2.json转str
使用json.dumps
的方法,可以将json
对象转化为字符串
import json
str = '{"name": "御姐", "age": 18}'
j = json.loads(str)
print(j)
j = json.dumps(j)
print(type(j))
3. 通过eval
eval函数的官方解释为:将字符串str当成有效的表达式来求值并返回计算结果。
即通过eval可以把list
,tuple
,dict
和string
相互转化,例如:
import json
a = "[[1,2], [3,4]]"
b = eval(a)
print(type(b))
a = "{1: 'a', 2: 'b'}"
b = eval(a)
print(type(b))
a = "([1,2], [3,4], [5,6], (9,0))"
b = eval(a)
print(type(b))
结果:
<class 'list'>
<class 'dict'>
<class 'tuple'>
来源:https://blog.csdn.net/Ghjkku/article/details/123312255
标签:Python,字符串,str,json格式,相互,转换
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
使用python 和 lint 删除项目无用资源的方法
2023-10-22 16:56:08
python 使用元类type创建类
2021-06-27 21:11:48
斜角滑动门导航条 DIV+CSS
2008-07-19 15:45:00
![](https://img.aspxhome.com/file/UploadPic/20087/19/200871916554645s.gif)
Python中按值来获取指定的键
2023-05-01 13:21:07
解决在window下执行SQLSERVER定时备份的问题
2024-01-13 15:17:09
![](https://img.aspxhome.com/file/2023/1/88261_0s.jpg)
如何应对SQL Server数据库崩溃
2008-11-24 17:25:00
Script的加载方法小结
2024-04-22 12:56:08
![](https://img.aspxhome.com/file/2023/0/136010_0s.png)
python中metaclass原理与用法详解
2023-11-26 23:27:56
python读取word 中指定位置的表格及表格数据
2021-04-10 02:42:21
![](https://img.aspxhome.com/file/2023/2/99622_0s.png)
django云端留言板实例详解
2023-12-13 08:17:59
python 实现简单的FTP程序
2021-03-29 10:33:00
![](https://img.aspxhome.com/file/2023/2/85382_0s.jpg)
10 个Python中Pip的使用技巧分享
2023-08-02 17:52:45
MySql子查询IN的执行和优化的实现
2024-01-15 01:32:10
![](https://img.aspxhome.com/file/2023/4/108924_0s.png)
Python内置函数—vars的具体使用方法
2021-05-07 04:09:57
在python中利用try..except来代替if..else的用法
2023-09-12 17:50:10
Python中的filter()函数的用法
2022-04-23 11:42:15
C#调用python.exe使用arcpy方式
2021-03-30 05:41:13
![](https://img.aspxhome.com/file/2023/8/71078_0s.jpg)
python DataFrame获取行数、列数、索引及第几行第几列的值方法
2023-08-19 18:12:13
Bootstrap源码解读按钮(5)
2023-08-23 01:16:51
python判断变量是否为列表的方法
2023-05-06 16:22:22
![](https://img.aspxhome.com/file/2023/9/109439_0s.png)