博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
python json模块使用示例
阅读量:4171 次
发布时间:2019-05-26

本文共 1273 字,大约阅读时间需要 4 分钟。

1》简介
json:标准化(序列化)的数据格式,几乎所有语言都支持的一种数据接口格式,
在python中,json可以方便地用来序列化常规的数据类型(字典,集合,列表等),
也可以序列化类的实例等,但比较麻烦。json序列化后的数据,可读性好,人能够识别。
2》序列化到内存对象 及 从内存反序列化的两种方法:

2.1》

import jsondict={'name':'song','sex':'man'}s=json.dumps(dict)#将字典 序列化成一个内存字符串,可读性好print sprint type(s)d=json.loads(s)#从内存对象反序列化print d
2.2》

import jsondict={'name':'song','sex':'man'}s=json.JSONEncoder().encode(dict)#将字典 序列化成一个内存字符串,可读性好print sprint type(s)d=json.JSONDecoder().decode(s)#从内存对象反序列化print d
3》序列化到文件的两种方式:
3.1》

import jsondict={'name':'song','sex':'man'}#将一个对象序列化成一个字符串,并保存在文件里f=open(r'C:\Users\91135\Desktop\wahaha.json','w')print f.tell()json.dump(dict,f)#序列化dict,把结果写入指定文件中print f.tell()f.close()
3.2》

import json  d={'name':'song','sex':'man'}f=open(r'C:\Users\91135\Desktop\wahaha.json','w')print f.tell()s=json.JSONEncoder().encode(d)print s,type(s)f.write(s)print f.tell()f.close()
4》从文件反序列化的两种方式(读取json文件的两种方式):
4.1》

import json  f=open(r'C:\Users\91135\Desktop\wahaha.json','r')print f.tell()source = f.read()  print f.tell()target = json.JSONDecoder().decode(source)  print targetprint type(target)f.close()
4.2》

import json  f=open(r'C:\Users\91135\Desktop\wahaha.json','r')print f.tell()target=json.load(f)#从文件中读取数据,并反序列化成原来的数据类型print f.tell()f.close()print targetprint type(target)
(完)

转载地址:http://mnyai.baihongyu.com/

你可能感兴趣的文章
【EVB-335X-II试用体验】 u-boot与kernel的编译以及本地repo的建立
查看>>
【EVB-335X-II试用体验】 上手试用与资源使用
查看>>
【EVB-335X-II试用体验】 Yocto环境的建立及Rootfs的构建与使用
查看>>
<<C++程序设计原理与实践>>粗读--chapter0 chapter1 chapter2
查看>>
<<C++程序设计原理与实践>>粗读--chapter3 chapter4 Chapter5
查看>>
<<C++程序设计原理与实践>>粗读 -- chapter8 Chapter9
查看>>
Linux Qt程序打包成一个可执行文件
查看>>
DragonBoard 410C中的Fastboot与调试串口注意事项
查看>>
跨系统的录音格式兼容性问题: iOS Android
查看>>
JVM 的垃圾回收器
查看>>
Mybatis的缓存
查看>>
@validated注解异常返回JSON值
查看>>
@JsonFormat注解使用
查看>>
Spring boot集成jxls实现导入功能
查看>>
Spring boot读取配置的方式(指定配置文件)
查看>>
Spring Boot切换不同环境配置
查看>>
Spring cloud之Ribbon搭建
查看>>
TreeMap 与 HashMap 的区别
查看>>
初识CAS
查看>>
Fork/Join 框架
查看>>