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 转成 类对象
[code]import jsonclass 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))# |