Python中Json使用示例详解
作者:AskaJohnny 时间:2021-01-17 00:43:43
Python Json使用
本篇主要介绍一下 python 中 json的使用 如何把 dict转成json 、object 转成json 、以及json转成对象 等等。。
json是非常常用的一种数据格式,比如在前后端分离的 web开发中,返回给前端 通常都会使用json ,那么来看看 python 中如何玩转json
1.dict 转成 json (json.dumps(dict))
注意: ensure_ascii=False 否则中文乱码
import json
student = {
'name': 'johnny',
'age': 27,
'address': '无锡'
}
print(json.dumps(student, ensure_ascii=False))
# {"name": "johnny", "age": 27, "address": "无锡"} json
2.json 转 dict (json.loads(jsonstr))
import json
json_student = '{"name": "johnny", "age": 27, "address": "无锡"}'
print(json.loads(json_student))
# {'name': 'johnny', 'age': 27, 'address': '无锡'} 字典dict
3. 类对象转 json (dict属性/提供default=方法)
3.1 错误使用
注意:json.dumps() 不支持 直接把 类对象放进去!!! 会报错 Student is not JSON serializable
import json
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
student = Student('candy', '30')
#错误使用!!!
print(json.dumps(student)) 报错!!! TypeError: Object of type Student is not JSON serializable
3.2 使用类对象 dict 属性
#正确使用!!!
print(json.dumps(student.__dict__))) #可以使用 类对象的 __dict__ 属性
#{"name": "candy", "age": "30"}
3.3 提供一个 convert2json 方法
default=指定方法
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
@staticmethod
def conver2json(self):
return {
'name': self.name,
'age': self.age
}
#通过自己写一个 conver2json方法 去手动转化一下 把 类对象转成json
print(json.dumps(student,default=Student.conver2json))
4.json 转 类对象 (json.loads(jsonstr,object_hook=..))
注意:json.loads 默认只会转成dict,需要自己提供方法 把dict 转成 类对象
import json
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
@staticmethod
def conver2json(self):
return {
'name': self.name,
'age': self.age
}
@staticmethod
def convert2object(dict):
return Student(dict['name'],dict['age'])
json_student = '{"name": "johnny", "age": 27, "address": "无锡"}'
print(json.loads(json_student,object_hook=Student.convert2object))
#<__main__.Student
5. dict/对象 转为 json文件 (json.dump(student,f))
注意 dump 还是 只能接收 dict ,如果要把 对象写到json中 需要先把对象 转成 dict ,可以通过 ——dict——属性
student = {
'name': 'johnny',
'age': 27,
'address': '无锡'
}
with open('student.json','w') as f:
json.dump(student,f,ensure_ascii=False)
6. json文件转 dict /对象 (json.load)
with open('student.json','r') as f:
print(json.load(f))
小疑问
为什么:转成json 后 name 是一个数组呢? 因为 self.name = name, 后面有一个 逗号,。。。 会把这个name当成元组 ,元组转成 json 就是 数组!!!
class Student:
def __init__(self, name, age):
self.name = name, #这里!!!不能有 逗号。。
self.age = age
student = Student('candy', '30')
print(json.dumps(student.__dict__))
#猜猜它的打印是什么
#{"name": ["candy"], "age": "30"}
来源:https://www.cnblogs.com/askajohnny/archive/2022/07/23/16511698.html
标签:Python,Json,使用
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
小小聊天室Python代码实现
2022-05-27 15:23:44
Python中关键字is与==的区别简述
2022-07-09 10:32:09
手把手带你了解python多进程,多线程
2021-07-16 02:08:42
![](https://img.aspxhome.com/file/2023/6/95446_0s.png)
Python批量修改xml的坐标值全部转为整数的实例代码
2021-10-29 00:57:50
![](https://img.aspxhome.com/file/2023/8/65548_0s.jpg)
Pycharm无法显示动态图片的解决方法
2023-01-29 23:13:42
![](https://img.aspxhome.com/file/2023/0/89420_0s.jpg)
Python math库 ln(x)运算的实现及原理
2023-09-11 18:12:28
![](https://img.aspxhome.com/file/2023/8/70228_0s.png)
numpy中的delete删除数组整行和整列的实例
2022-11-24 22:09:01
![](https://img.aspxhome.com/file/2023/5/97365_0s.jpg)
利用Python如何生成hash值示例详解
2022-02-28 23:29:25
如何使用Python的Requests包实现模拟登陆
2022-10-07 03:12:26
![](https://img.aspxhome.com/file/2023/3/75123_0s.png)
Python趣味挑战之用pygame实现飞机塔防游戏
2022-07-18 04:00:02
![](https://img.aspxhome.com/file/2023/7/95867_0s.gif)
如何在sublime编辑器中安装python
2021-01-12 05:27:00
![](https://img.aspxhome.com/file/2023/9/108119_0s.png)
利用Python+PyQt5实现简易浏览器的实战记录
2022-10-30 23:16:26
![](https://img.aspxhome.com/file/2023/3/77853_0s.png)
python中正则表达式的使用方法
2021-08-14 09:36:59
从JavaScript的函数重名看其初始化方式
2023-07-16 22:00:12
![](https://img.aspxhome.com/file/2023/3/55923_0s.gif)
torch 中各种图像格式转换的实现方法
2021-04-17 08:08:13
python GUI库图形界面开发之PyQt5中QMainWindow, QWidget以及QDialog的区别和选择
2022-04-22 01:39:50
利用Python网络爬虫爬取各大音乐评论的代码
2023-01-05 19:26:55
![](https://img.aspxhome.com/file/2023/6/95466_0s.png)
四种方法在SQL Server数据库中成批导入数据
2009-02-19 17:25:00
jquery的$(document).ready()和onload的加载顺序
2023-08-23 18:57:40
python中SSH远程登录设备的实现方法
2023-10-24 02:30:58
![](https://img.aspxhome.com/file/2023/7/80787_0s.png)