未提供项目说明

json-kit的Python项目详细描述


安装

  • 从python包索引
pipinstalljson_kit
  • 下载包并运行设置.py在
^{pr2}$

用法

使用SimpleJSONEncoder序列化枚举和自定义类

fromenumimportEnumfromjson_kitimportSimpleJSONEncoderclassJob(Enum):Teacher=0Engineer=1Doctor=2hobbies=["Swimming","Video Games","Fishing"]# If reference keeping is not required, no need to impl __hash__, __eq__classPerson:def__init__(self,name,age,job,hobbies):self.name=nameself.age=ageself.job=jobself.hobbies=hobbiesjack=Person('Jack',33,Job.Teacher)withopen(json_path,'w')asfp:json.dump(jack,fp,cls=SimpleJSONEncoder)# output string# {"name": "Jack", "age": 33, "job": 0, "hobbies": ["Swimming", "Video Games", "Fishing"]}

使用RefJSONEncoder序列化并保留自定义的类引用

  • 为类实现散列和eq帴,以保留其引用
  • 不保留诸如list/dict/set/tuple引用之类的内置collector
fromjson_kitimportRefJSONEncoder,is_customized_class,hashable,to_hashable# Should implement __hash__ and __eq__ for certain custom class# if its reference keeping is intended;# and don't impl both __hash__ and __eq__ for classes # if reference keeping is not intended (when using RefJSONEncoder or AllRefJSONEncoder)classPerson:def__init__(self,name,age,job,hobbies):self.name=nameself.age=ageself.job=jobself.hobbies=hobbiesdef__hash__(self):data=[(k,v)ifhashable(v)else(k,to_hashable(v))fork,vinself.__dict__.items()]data.sort(key=lambdax:x[0])data=tuple(data)returnhash(data)def__eq__(self,other):ifnotis_customized_class(other)ornothashable(other):returnFalsereturnself.__class__==other.__class__andself.__hash__()==other.__hash__()jack=Person('Jack',33,Job.Doctor)another_jack=Person('Jack',33,Job.Doctor)jacks=[jack,another_jack]withopen(json_path,'w')asfp:json.dump(jacks,fp,cls=RefJSONEncoder)# output string:# [{"$id": "1", "name": "Jack", "age": 33, "job": 0, "hobbies": ["Swimming", "Video Games", "Fishing"]}, {"$ref": "1"}]

使用AllRefJSONEncoder序列化并保留自定义类、list(set/tuple)、dict的引用

  • 为类实现散列和eq帴,以保留其引用
  • 保留了诸如list/dict/set/tuple等内置的collector(set/tuple被转换成list)。在
  • 使用IList/IDictionary而不是C\35;中的IReadOnlyList/IReadOnlyDictionary,否则Json.net网站反序列化时无法呈现内置集合引用。在
fromjson_kitimportRefJSONEncoder,is_customized_class,hashable,to_hashable# Should implement __hash__ and __eq__ for certain custom class# if its reference keeping is intendedclassPerson:def__init__(self,name,age,job,hobbies):self.name=nameself.age=ageself.job=jobself.hobbies=hobbiesdef__hash__(self):data=[(k,v)ifhashable(v)else(k,to_hashable(v))fork,vinself.__dict__.items()]data.sort(key=lambdax:x[0])data=tuple(data)returnhash(data)def__eq__(self,other):ifnotis_customized_class(other)ornothashable(other):returnFalsereturnself.__class__==other.__class__andself.__hash__()==other.__hash__()jack=Person('Jack',33,Job.Teacher,hobbies)another_jack=Person('Jack',33,Job.Teacher,hobbies)mike=Person('Mike',24,Job.Doctor,hobbies)persons=[jack,another_jack,mike]withopen(json_path,'w')asfp:json.dump(persons,fp,cls=AllRefJSONEncoder)# output text:# [{"$id": "1", "name": "Jack", "age": 33, "job": 0, "hobbies": {"$id": "2", "$values": ["Swimming", "Video Games", "Fishing"]}}, {"$ref": "1"}, {"name": "Mike", "age": 24, "job": 2, "hobbies": {"$ref": "2"}}]

禁用skip_none_字段以保留空字段

# Note# None fields in cusomized classes are skipped in default.# Set Encoder.skip_none_fields = False to preserve none fields.person=Person('Jack',Job.Teacher,hobbies)person.age=Nonejstr=json.dumps(obj,cls=SimpleJSONEncoder)# output string# {"name": "Jack", "job": 0, "hobbies": ["Swimming", "Video Games", "Fishing"]}SimpleJSONEncoder.skip_none_fieds=Falsejstr=json.dumps(obj,cls=SimpleJSONEncoder)# output string# {"name": "Jack", "age": null, "job": 0, "hobbies": ["Swimming", "Video Games", "Fishing"]}

使用serialize_only_annotated仅序列化带注释的字段

  • 若要仅序列化部分实例字段,请在类级别对要序列化的字段进行注释
  • 如果类级别上不存在注释,则所有实例字段都将被序列化
fromtypingimportListfromjson_kitimportSimpleJSONEncoderclassPerson:name:strage:intjob:Jobhobbies:List[str]def__init__(self,name,age,job,hobbies,address):self.name=nameself.age=ageself.job=jobself.hobbies=hobbiesself.address=addressperson=Person('Jack',33,Job.Teacher,hobbies,'Chengdu')SimpleJSONEncoder.serialize_only_annotated=Truejstr=json.dumps(person,cls=SimpleJSONEncoder)# output string# {"name": "Jack", "age": 33, "job": 0, "hobbies": ["Swimming", "Video Games", "Fishing"]}# if no annotation is provided, then all fields will be serialized, including 'address' field.

使用加载json_文件进行自动编码检测

fromjson_kitimportload_json_filefilename="./sample.json"obj=load_json_file(filename)

欢迎加入QQ群-->: 979659372 Python中文网_新手群

推荐PyPI第三方库


热门话题
java从Dropwizard中的Minio检索文件时,GET请求中的超时是如何处理的?   带Hibernate的java Jackson用于序列化以避免枚举   Raspberry Pi上的java Jave分段错误   java在屏幕旋转时不保存当前片段和数据   java War文件未在Heroku上正确部署   如何使用Java处理Selenium webdriver中的促销广告或cookie   java处理“用法:PApplet[options]<classname>[sketch args]”   java文本文件错误扫描程序   运行第一个JavaFX模块化程序时出现java异常   java将fileoutputstream转换为字符串   如何调试gstreamerjava?   java Spring RestTemplate ResponseBody类是什么样的   如何将JSON数组转换为Java列表。我在用斯文森   javascript在显示div按钮后进入新页面