ToB企服应用市场:ToB评测及商务社交产业平台

标题: Python Json使用 [打印本页]

作者: 莫张周刘王    时间: 2022-8-31 07:44
标题: Python Json使用
Python Json使用

本篇主要介绍一下 python 中 json的使用 如何把 dict转成json 、object 转成json  、以及json转成对象 等等。。
json是非常常用的一种数据格式,比如在前后端分离的 web开发中,返回给前端 通常都会使用json ,那么来看看 python 中如何玩转json
1.dict 转成 json (json.dumps(dict))

注意: ensure_ascii=False 否则中文乱码
  1. import json
  2. student = {
  3.      'name': 'johnny',
  4.      'age': 27,
  5.      'address': '无锡'
  6. }
  7. print(json.dumps(student, ensure_ascii=False))
  8. # {"name": "johnny", "age": 27, "address": "无锡"}  json
复制代码
2.json 转 dict  (json.loads(jsonstr))
  1. import json
  2. json_student = '{"name": "johnny", "age": 27, "address": "无锡"}'
  3. print(json.loads(json_student))
  4. # {'name': 'johnny', 'age': 27, 'address': '无锡'} 字典dict
复制代码
3. 类对象转 json (dict属性/提供default=方法)

3.1 错误使用

注意:json.dumps() 不支持 直接把 类对象放进去!!! 会报错 Student is not JSON serializable
  1. import json
  2. class Student:
  3.     def __init__(self, name, age):
  4.         self.name = name
  5.         self.age = age
  6.         
  7. student = Student('candy', '30')
  8. #错误使用!!!
  9. print(json.dumps(student))  报错!!! TypeError: Object of type Student is not JSON serializable
复制代码
3.2 使用类对象  dict  属性
  1. #正确使用!!!
  2. print(json.dumps(student.__dict__))) #可以使用 类对象的 __dict__ 属性
  3. #{"name": "candy", "age": "30"}
复制代码
3.3 提供一个 convert2json 方法

default=指定方法
  1. class Student:
  2.     def __init__(self, name, age):
  3.         self.name = name
  4.         self.age = age
  5.    
  6.     @staticmethod
  7.     def conver2json(self):
  8.         return {
  9.             'name': self.name,
  10.             'age': self.age
  11.         }
  12. #通过自己写一个 conver2json方法 去手动转化一下 把 类对象转成json
  13. 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))#




欢迎光临 ToB企服应用市场:ToB评测及商务社交产业平台 (https://dis.qidao123.com/) Powered by Discuz! X3.4