java中的接口是类吗
243
2022-08-27
Python从门到精通(五):文件处理-03-Json文件处理(python输出json文件)
需要引入json库
一、json库的使用
import jsondata = { 'course' : 'python', 'total_class' : 30, 'score' : 0.3}#str2jsonjson_str = json.dumps(data)#json2strdata = json.loads(json_str)# Writing JSON datawith open('data.json', 'w') as f: json.dump(data, f)# Reading data backwith open('data.json', 'r') as f: data = json.load(f)#类型设置dumps result: {"a": true, "b": "Hello", "c": null}print(json.dumps(False))str_dict = {'a': True, 'b': 'Hello', 'c': None }print(f'dumps result: {json.dumps(str_dict)}')
二、自定义json返回类型
#一般来说json会返回dict或list,可通过object_hook或object_pairs_hook自定义s = '{"course": "python", "total_class": 30, "score": 0.3}'from collections import OrderedDictdata = json.loads(s, object_pairs_hook=OrderedDict)print(f'data loads: {data}')#转换为json对象class JSONObject: def __init__(self, d): self.__dict__ = ddata = json.loads(s, object_hook=JSONObject)print(f'course is: {data.course}')print(f'total class is: {data.total_class}')print(f'score is: {data.score}')
三、序列化与反序列化
一般对象实例都不是可以序列化的,需要自定义实现
class Point: def __init__(self, x, y): self.x = x self.y = yp = Point(1, 3)# print(f'dumps: {json.dumps(p)}')def serialize_instance(obj): d = { '__classname__' : type(obj).__name__ } d.update(vars(obj)) return d# Dictionary mapping names to known classesclasses = { 'Point' : Point}def unserialize_object(d): # clsname = d.pop('__classname__', None) if (clsname := d.pop('__classname__', None)): cls = classes[clsname] obj = cls.__new__(cls) # Make instance without calling __init__ for key, value in d.items(): setattr(obj, key, value) return obj else: return dp = Point(2,3)s = json.dumps(p, default=serialize_instance)a = json.loads(s, object_hook=unserialize_object)print(f'json loads: {a}')print(f'a x is: {a.x}')print(f'a y is: {a.y}')
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
发表评论
暂时没有评论,来抢沙发吧~