美文网首页
python 序列化

python 序列化

作者: RayRaymond | 来源:发表于2020-05-24 12:11 被阅读0次

    定义

    Serialization 系列化,将内存中对象存储下来,把他变成一个个字节。二进制。

    deSerialization 反序列化,将文件的一个个字节到内存中。

    可将数据序列化后持久化,或者网络传输,也可以将文件中或者网络接受到的字节序列反序列化。

    pickle

    pickle.dumps()方法把任意对象序列化成一个bytes

    序列化和反序列化

    import pickle
    
    
    d = {'name': 'Luffy', 'age': 18, 'score': 100}
    
    # 序列化
    with open('d.txt','wb') as ds:
        pickle.dump(d,ds)
        print('serialized')
    
    # 反序列化
    with open('d.txt','rb') as data:
        data_load = pickle.load(data)
        print(data_load)
    
    # serialized
    # {'name': 'Luffy', 'age': 18, 'score': 100}
    

    因为存在python版本不兼容的问题,所以只能用Pickle保存那些不重要的、不能成功地反序列化也没关系的数据

    序列化类

    其实是序列化对象的属性

    import pickle
    
    class Stu(object):
        def __init__(self):
            self.name = 'ray'
            self.age = 25
    
    
    ray = Stu()
    with open('stu.txt','wb') as d:
        pickle.dump(ray,d)
    
    with open('stu.txt','rb') as d:
        st = pickle.load(d)
        print(st.name,st.age)
        # ray 25
    

    JSON

    • 只支持部分数据类型
    Python类型 Json类型
    True True
    False False
    None Null
    Str String
    Int Integer
    Float Float
    List Array
    Dict obiect
    Python 类型 Json类型
    Dumps Json编码
    Dump Json编码并写入文件
    Loads Json解码
    Load Json解码,从文件读取数据

    序列化

    import json
    historyTransactions = [
    
        {
            'time'   : '20170101070311',  # 交易时间
            'amount' : '3088',            # 交易金额
            'productid' : '45454455555',  # 货号
            'productname' : 'iphone7'     # 货名
        },
        {
            'time'   : '20170101050311',  # 交易时间
            'amount' : '18',              # 交易金额
            'productid' : '453455772955', # 货号
            'productname' : '奥妙洗衣液'   # 货名
        }
    
    ]
    
    # dumps 方法将数据对象序列化为 json格式的字符串
    jsonstr = json.dumps(historyTransactions)
    print(jsonstr)
    
    • json.dumps 方法发现将字符串中如果有非ascii码字符,比如中文, 缺省就用该字符的unicode数字来表示。

      json.dumps(historyTransactions,ensure_ascii=False,indent=4)
      

      indent参数表示转换后缩进为4

      ensure_ascii=False解决字符缺省

    反序列化

    import json
    jsonstr = '[{"time": "20170101070311", "amount": "3088", "productid": "45454455555", "productname": "iphone7"}, {"time": "20170101050311", "amount": "18", "productid": "453455772955", "productname": "\u5965\u5999\u6d17\u8863\u6db2"}]'
    
    translist = json.loads(jsonstr)
    print(translist)
    print(type(translist))
    
    # [{'time': '20170101070311', 'amount': '3088', 'productid': '45454455555', 'productname': 'iphone7'}, {'time': '20170101050311', 'amount': '18', 'productid': '453455772955', 'productname': '奥妙洗 衣液'}]
    
    # <class 'list'>
    

    相关文章

      网友评论

          本文标题:python 序列化

          本文链接:https://www.haomeiwen.com/subject/kgwdahtx.html