zoukankan      html  css  js  c++  java
  • 序列化模块

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

    比如,我们在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、使程序更具维护性。

    一、序列化之Json模块
    Json模块提供了四个功能:dumps、dump、loads、load
    dumps loads 字符串 和 其他基础数据类型之间转换
    dump load 文件 和 其他基础数据类型之间转换

    dumps loads 字符串 和 其他基础数据类型之间转换

    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'}]
    

      

    import json
    # 坑1:json格式规定字典所有的key必须是字符串数据类型,否者经过dumps - loads 所以的key默认变成字符串数据类型
    dic = {1:2}
    ret = json.dumps(dic)
    print(dic[1])
    print(ret)
    new_dic = json.loads(ret)
    print(new_dic)
    
    # 坑2 : json中的所有tuple都会被当作list处理
    dic = (1,2,3)
    ret = json.dumps(dic)
    print(ret)
    new_dic = json.loads(ret)
    print(new_dic)
    
    dic = {1:(1,2,3)}
    ret = json.dumps(dic)
    print(ret)
    new_dic = json.loads(ret)
    print(new_dic)
    
    # 特性3: json能支持的数据类型非常有限,字符串 数字 列表 字典
    dic = {(1,2):(1,2,3)}
    ret = json.dumps(dic)
    print(dic)
    new_dic = json.loads(ret)
    print(new_dic)
    

      


    dump load 文件 和 其他基础数据类型之间转换

    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)
    
    # json不可以dump多次(虽然可以dump多次,但是:由于dump多次之后,当loads时不知道是多少次或报错,所以干脆就说dump不可以多次)
    dic = {"key":"value"}
    with open('json_file2','w') as f:
        json.dump(dic,f)
        json.dump(dic,f)
    
    str_dic = {"name": "alex","sex":None}
    ret = json.dumps(str_dic)
    with open('json_file2','w') as f:
        f.write(ret+'\n')
    

      


    dumps与dump的ensure_ascii关键字参数

    在使用json.dumps时要注意一个问题
    >>> import json
    >>> print json.dumps('中国')
    "\u4e2d\u56fd" 
    输出的会是
    '中国' 中的ascii 字符码,而不是真正的中文。
    这是因为json.dumps 序列化时对中文默认使用的ascii编码.想输出真正的中文需要指定ensure_ascii=False:
    >>> import json
    >>> print json.dumps('中国')
    "\u4e2d\u56fd"
    >>> print json.dumps('中国',ensure_ascii=False)
    "中国"
    >>>
    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()
    

      

    dumps与dump的其它参数

    Serialize obj to a JSON formatted str.(将obj序列化为JSON格式的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)
    

      


    二、序列化之pickle模块
    pickle模块提供了四个功能:dumps、dump(序列化,存)、loads(反序列化,读)、load (不仅可以序列化字典,列表...可以把python中任意的数据类型序列化)
    pickle
    1.支持几乎所有python中的数据类型
    2.只在python语言中通用
    3.pickle适合bytes类型打交道的

    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')
    pickle.dump(struct_time,f)
    f.close()
    
    f = open('pickle_file','rb')
    struct_time2 = pickle.load(f)
    print(struct_time2.tm_year)
    

      

    import pickle
    # s = {1,2,3,4}
    # s = {1:2,3:4}
    s = {(1,2,3):2,3:4}
    result = pickle.dumps(s)
    print(result)
    with open('pickle_file','wb') as f:
        f.write(result)
    new_s = pickle.loads(result)
    print('new_s :',new_s)
    
    with open('pickle_file','rb') as f:
        content = f.read()
    ret = pickle.loads(content)
    print(ret,type(ret))
    
    # pickle 可以支持多个对象放入文件
    s1 = {1,2,3}
    s2 = {1:2,3:4}
    s3 = ['k','v',(1,2,3),4]
    with open('pickle_file2','wb') as f:
        pickle.dump(s1,f)
        pickle.dump(s2,f)
        pickle.dump(s3,f)
    
    with open('pickle_file2','rb') as f:
        count = 1
        while count <= 3:
            try:
                content = pickle.load(f)
                print(content)
                count += 1
            except EOFError:
                break
    			
    

      


    三、pickle和json的区别

    这时候机智的你又要说了,既然pickle如此强大,为什么还要学json呢?
    这里我们要说明一下,json是一种所有(大多数高级)的语言都可以识别的数据结构。
    如果我们将一个字典或者序列化成了一个json存在文件里,那么java代码或者js代码也可以拿来用。
    但是如果我们用pickle进行序列化,其他语言就不能读懂这是什么了~
    所以,如果你序列化的内容是列表或者字典,我们非常推荐你使用json模块
    但如果出于某种原因你不得不序列化其他的数据类型,而未来你还会用python对这个数据进行反序列化的话,那么就可以使用pickle
    
    json
    如果你是要跨平台沟通,那么推荐使用json
    key只能是字符串
    不能多次load和dump
    支持的数据类型有限
    
    pickle
    如果你是只在python程序之间传递消息,并且要传递的消息是比较特殊的数据类型
    处理文件的时候 rb/wb
    支持多次dump/load
    
    
    json,用于字符串 和 python数据类型间进行转换
    pickle,用于python特有的类型 和 python的数据类型间进行转换



  • 相关阅读:
    Java 8 Lambda 表达式
    OSGi 系列(十二)之 Http Service
    OSGi 系列(十三)之 Configuration Admin Service
    OSGi 系列(十四)之 Event Admin Service
    OSGi 系列(十六)之 JDBC Service
    OSGi 系列(十)之 Blueprint
    OSGi 系列(七)之服务的监听、跟踪、声明等
    OSGi 系列(六)之服务的使用
    OSGi 系列(三)之 bundle 事件监听
    OSGi 系列(三)之 bundle 详解
  • 原文地址:https://www.cnblogs.com/linux985/p/10334924.html
Copyright © 2011-2022 走看看