当前位置: 首页 > news >正文

Python-序列化模块-json-62

序列化模块

 

Eva_J

什么叫序列化——将原本的字典、列表等内容转换成一个字符串的过程就叫做序列化

比如,我们在python代码中计算的一个数据需要给另外一段程序使用,那我们怎么给?
现在我们能想到的方法就是存在文件里,然后另一个python程序再从文件里读出来。
但是我们都知道,对于文件来说是没有字典这个概念的,所以我们只能将数据转换成字典放到文件中。
你一定会问,将字典转换成一个字符串很简单,就是str(dic)就可以办到了,为什么我们还要学习序列化模块呢?
没错序列化的过程就是从dic 变成str(dic)的过程。现在你可以通过str(dic),将一个名为dic的字典转换成一个字符串,
但是你要怎么把一个字符串转换成字典呢?
聪明的你肯定想到了eval(),如果我们将一个字符串类型的字典str_dic传给eval,就会得到一个返回的字典类型了。
eval()函数十分强大,但是eval是做什么的?e官方demo解释为:将字符串str当成有效的表达式来求值并返回计算结果。
BUT!强大的函数有代价。安全性是其最大的缺点。
想象一下,如果我们从文件中读出的不是一个数据结构,而是一句"删除文件"类似的破坏性语句,那么后果实在不堪设设想。
而使用eval就要担这个风险。
所以,我们并不推荐用eval方法来进行反序列化操作(将str转换成python中的数据结构)

为什么要有序列化模块

 

序列化的目的

1、以某种存储形式使自定义 对象持久化;
2、将对象从一个地方传递到另一个地方。
3、使程序更具维护性。

 

 

'abdsafaslhiewhldvjlmvlvk['
# 序列化 —— 转向一个字符串数据类型
# 序列 —— 字符串


"{'k':'v'}"

# 数据存储
# 网络上传输的时候

# 从数据类型 --> 字符串的过程 序列化
# 从字符串 --> 数据类型的过程 反序列化

 

# json *****
# pickle ****
# shelve ***

# json  # 数字 字符串 列表 字典 元组
    # 通用的序列化格式
    # 只有很少的一部分数据类型能够通过json转化成字符串
# pickle
    # 所有的python中的数据类型都可以转化成字符串形式
    # pickle序列化的内容只有python能理解
    # 且部分反序列化依赖python代码
# shelve
    # 序列化句柄
    # 使用句柄直接操作,非常方便

 

json

Json模块提供了四个功能:dumps、dump、loads、load

import json
dic = {'k1':'v1','k2':'v2','k3':'v3'}
str_dic = json.dumps(dic)  #序列化:将一个字典转换成一个字符串
print(type(str_dic),str_dic)  #<class 'str'> {"k3": "v3", "k1": "v1", "k2": "v2"}
#注意,json转换完的字符串类型的字典中的字符串是由""表示的

dic2 = json.loads(str_dic)  #反序列化:将一个字符串格式的字典转换成一个字典
#注意,要用json的loads功能处理的字符串类型的字典中的字符串必须由""表示
print(type(dic2),dic2)  #<class 'dict'> {'k1': 'v1', 'k2': 'v2', 'k3': 'v3'}


list_dic = [1,['a','b','c'],3,{'k1':'v1','k2':'v2'}]
str_dic = json.dumps(list_dic) #也可以处理嵌套的数据类型 
print(type(str_dic),str_dic) #<class 'str'> [1, ["a", "b", "c"], 3, {"k1": "v1", "k2": "v2"}]
list_dic2 = json.loads(str_dic)
print(type(list_dic2),list_dic2) #<class 'list'> [1, ['a', 'b', 'c'], 3, {'k1': 'v1', 'k2': 'v2'}]

loads和dumps

 

import json
f = open('json_file','w')
dic = {'k1':'v1','k2':'v2','k3':'v3'}
json.dump(dic,f)  #dump方法接收一个文件句柄,直接将字典转换成json字符串写入文件
f.close()

f = open('json_file')
dic2 = json.load(f)  #load方法接收一个文件句柄,直接将文件中的json字符串转换成数据结构返回
f.close()
print(type(dic2),dic2)

load和dump

 

import json
f = open('file','w')
json.dump({'国籍':'中国'},f)
ret = json.dumps({'国籍':'中国'})
f.write(ret+'\n')
json.dump({'国籍':'美国'},f,ensure_ascii=False)
ret = json.dumps({'国籍':'美国'},ensure_ascii=False)
f.write(ret+'\n')
f.close()

ensure_ascii关键字参数

 

Serialize obj to a JSON formatted str.(字符串表示的json对象) 
Skipkeys:默认值是False,如果dict的keys内的数据不是python的基本类型(str,unicode,int,long,float,bool,None),设置为False时,就会报TypeError的错误。此时设置成True,则会跳过这类key 
ensure_ascii:,当它为True的时候,所有非ASCII码字符显示为\uXXXX序列,只需在dump时将ensure_ascii设置为False即可,此时存入json的中文即可正常显示。) 
If check_circular is false, then the circular reference check for container types will be skipped and a circular reference will result in an OverflowError (or worse). 
If allow_nan is false, then it will be a ValueError to serialize out of range float values (nan, inf, -inf) in strict compliance of the JSON specification, instead of using the JavaScript equivalents (NaN, Infinity, -Infinity). 
indent:应该是一个非负的整型,如果是0就是顶格分行显示,如果为空就是一行最紧凑显示,否则会换行且按照indent的数值显示前面的空白分行显示,这样打印出来的json数据也叫pretty-printed json 
separators:分隔符,实际上是(item_separator, dict_separator)的一个元组,默认的就是(‘,’,’:’);这表示dictionary内keys之间用“,”隔开,而KEY和value之间用“:”隔开。 
default(obj) is a function that should return a serializable version of obj or raise TypeError. The default simply raises TypeError. 
sort_keys:将数据根据keys的值进行排序。 
To use a custom JSONEncoder subclass (e.g. one that overrides the .default() method to serialize additional types), specify it with the cls kwarg; otherwise JSONEncoder is used.

其他参数说明

 

import json
data = {'username':['李华','二愣子'],'sex':'male','age':16}
json_dic2 = json.dumps(data,sort_keys=True,indent=2,separators=(',',':'),ensure_ascii=False)
print(json_dic2)

 

import json

dic = {1:"a", 2:"b"}
f = open('fff', 'w', encoding='utf-8')
json.dump(dic, f)
f.close()

 

import json

f = open('fff',encoding='utf-8')
res1 = json.load(f)
f.close()
print(type(res1),res1) # <class 'dict'> {'1': 'a', '2': 'b'}

 

import json
# # json dump load
dic = {1:"中国",2:'b'}
f = open('fff','w',encoding='utf-8')
json.dump(dic,f,ensure_ascii=False)
json.dump(dic,f,ensure_ascii=False)
# f.close()
f = open('fff',encoding='utf-8')
res1 = json.load(f) #报错 不能同时读两条
# res2 = json.load(f)
f.close()
print(type(res1),res1)
# print(type(res2),res2)

 

# json
# dumps {} -- > '{}\n'
# 一行一行的读
# '{}\n'
# '{}' loads
l = [{'k':'111'},{'k2':'111'},{'k3':'111'}]
f = open('file','w')
import json
for dic in l:
    str_dic = json.dumps(dic)
    f.write(str_dic+'\n')
f.close()

 

 

f = open('file')
import json
for line in f:
    dic = json.loads(line.strip()) #一行一行的将json格式的数据读出来
    print(dic)
    '''
    {'k': '111'}
    {'k2': '111'}
    {'k3': '111'}
    '''
f.close()

 

f = open('file')
import json
l = []
for line in f:
    dic = json.loads(line.strip())
    l.append(dic) # 转化为列表的方式重新拿出来
f.close()
print(l) #输出

 

pickle

 

json & pickle 模块

 

用于序列化的两个模块

 

  • json,用于字符串 和 python数据类型间进行转换
  • pickle,用于python特有的类型 和 python的数据类型间进行转换

 

pickle模块提供了四个功能:dumps、dump(序列化,存)、loads(反序列化,读)、load  (不仅可以序列化字典,列表...可以把python中任意的数据类型序列化

 

import pickle
dic = {'k1':'v1','k2':'v2','k3':'v3'}
str_dic = pickle.dumps(dic)
print(str_dic)  #一串二进制内容

dic2 = pickle.loads(str_dic)
print(dic2)    #字典

import time
struct_time  = time.localtime(1000000000)
print(struct_time)
f = open('pickle_file','wb') #byte 类型所以要用wb写入
pickle.dump(struct_time,f)
f.close()

f = open('pickle_file','rb') # rb 方式读
struct_time2 = pickle.load(f)
print(struct_time2.tm_year)

pickle

 

import time
struct_time1  = time.localtime(1000000000)
struct_time2  = time.localtime(2000000000)
f = open('pickle_file','wb')
pickle.dump(struct_time1,f)
pickle.dump(struct_time2,f)
f.close()
f = open('pickle_file','rb')
struct_time1 = pickle.load(f)
struct_time2 = pickle.load(f)
print(struct_time1.tm_year)
print(struct_time2.tm_year)
f.close() 
# 对于pickle 来说可以分布的dump 和分布的 load ,但是对于 json 来说就不可以
 

 

 

这时候机智的你又要说了,既然pickle如此强大,为什么还要学json呢?
这里我们要说明一下,json是一种所有的语言都可以识别的数据结构。
如果我们将一个字典或者序列化成了一个json存在文件里,那么java代码或者js代码也可以拿来用。
但是如果我们用pickle进行序列化,其他语言就不能读懂这是什么了~
所以,如果你序列化的内容是列表或者字典,我们非常推荐你使用json模块
但如果出于某种原因你不得不序列化其他的数据类型,而未来你还会用python对这个数据进行反序列化的话,那么就可以使用pickle

 

 

shelve:

import shelve
f = shelve.open('shelve_file')
f['key'] = {'int':10, 'float':9.5, 'string':'Sample data'}  #直接对文件句柄操作,就可以存入数据
f.close()
#
import shelve
f1 = shelve.open('shelve_file')
existing = f1['key']  #取出数据的时候也只需要直接用key获取即可,但是如果key不存在会报错
f1.close()
print(existing)

 

import shelve
f = shelve.open('shelve_file', flag='r')
existing = f['key']
print(existing) # {'int': 10, 'float': 9.5, 'string': 'Sample data'}
f['key'] = 50
f.close()

f = shelve.open('shelve_file', flag='r')
existing2 = f['key']
f.close()
print(existing2) # 50

 

import shelve
f = shelve.open('shelve_file', flag='r')
existing = f['key']
print(existing) # {'int': 10, 'float': 9.5, 'string': 'Sample data'}
f['key'] = 50
f.close()

f = shelve.open('shelve_file', flag='r')
existing2 = f['key']
f.close()
print(existing2) # 50

import shelve
f1 = shelve.open('shelve_file')
print(f1['key'])
f1['key']['new_value'] = 'this was not here before'
f1.close()

f2 = shelve.open('shelve_file', writeback=True) # writeback=True 可修改文件
print(f2['key']) f2['key']['new_value'] = 'this was not here before' f2.close()

 

转载于:https://www.cnblogs.com/LXL616/p/10730115.html

相关文章:

  • 虚拟机上 安装 CentoOS 7.5 1804 过程记录
  • npm ERR! Unexpected end of JSON input while parsing near
  • python socket文件传输实现
  • BZOJ3711 Druzyny 最值分治、线段树
  • jmeter5.1企业级应用功能详解
  • 面向对象的三大特性之封装
  • 数据结构:自定义数组队列
  • 异或的性质及运用
  • 20175215 2018-2019-2 第八周java课程学习总结
  • 我的java问题排查工具单
  • 记录一个pom文件
  • 2.4 hive创建表实例讲解
  • Cookie Session和自定义分页
  • SSM框架的优势?
  • 获得小黄衫有感
  • 【Amaple教程】5. 插件
  • 【跃迁之路】【444天】程序员高效学习方法论探索系列(实验阶段201-2018.04.25)...
  • axios 和 cookie 的那些事
  • CSS实用技巧干货
  • ECS应用管理最佳实践
  • electron原来这么简单----打包你的react、VUE桌面应用程序
  • Hibernate最全面试题
  • js对象的深浅拷贝
  • markdown编辑器简评
  • PHP的Ev教程三(Periodic watcher)
  • Python 使用 Tornado 框架实现 WebHook 自动部署 Git 项目
  • Vue学习第二天
  • 笨办法学C 练习34:动态数组
  • 复杂数据处理
  • 如何在 Tornado 中实现 Middleware
  • 腾讯视频格式如何转换成mp4 将下载的qlv文件转换成mp4的方法
  • 为什么要用IPython/Jupyter?
  • 我的业余项目总结
  • 在weex里面使用chart图表
  • 主流的CSS水平和垂直居中技术大全
  • 好程序员大数据教程Hadoop全分布安装(非HA)
  • ​决定德拉瓦州地区版图的关键历史事件
  • #git 撤消对文件的更改
  • #QT(智能家居界面-界面切换)
  • #免费 苹果M系芯片Macbook电脑MacOS使用Bash脚本写入(读写)NTFS硬盘教程
  • #使用清华镜像源 安装/更新 指定版本tensorflow
  • (C)一些题4
  • (C语言)球球大作战
  • (官网安装) 基于CentOS 7安装MangoDB和MangoDB Shell
  • (算法二)滑动窗口
  • (未解决)macOS matplotlib 中文是方框
  • (转)EXC_BREAKPOINT僵尸错误
  • *Algs4-1.5.25随机网格的倍率测试-(未读懂题)
  • .NET Micro Framework初体验(二)
  • .NET/C# 异常处理:写一个空的 try 块代码,而把重要代码写到 finally 中(Constrained Execution Regions)
  • .NET建议使用的大小写命名原则
  • /proc/vmstat 详解
  • @cacheable 是否缓存成功_Spring Cache缓存注解
  • []串口通信 零星笔记
  • [BT]小迪安全2023学习笔记(第15天:PHP开发-登录验证)