#!/usr/bin/env python # -*- Coding:utf-8 -*- import json d = dict(name='Bob', age=20, score=88) with open('json.txt', 'w') as e: e.write(json.dumps(d)) print(json.dumps(d)) with open('json.txt', 'r') as f: print(json.loads(f.read())) with open('json2.txt', 'w') as g: json.dump(d, g) with open('json2.txt', 'r', encoding='utf-8') as h: print(json.load(h)) class Student(object): def __init__(self, name, age, score): self.name = name self.age = age self.score = score s = Student('Bob', 20, 88) print(json.dumps(s, default=lambda obj: obj.__dict__)) # 将class转化为dict后才可进行序列化 odd = dict(name='小明', age=20) b = json.dumps(odd, ensure_ascii=True) print(b)
Python json序列化与反序列化
最新推荐文章于 2024-05-13 21:52:19 发布