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

    json模块

    什么是json?

    json是一个序列化模块,json是一个'第三方'的特殊数据格式

    为什么要使用json?

    为了让不同语言之间的数据可以共享

    PS:由于各种语言的数据类型不一,但样子(表现形式)可能一样。

    比如python不能直接使用其他语言的数据类型,

    必须将其他语言的数据类型转换成json数据格式,

    python获取到json数据后可以将json转换成python的数据类型

    作用为

    可以将python数据类型,先转化为json数据格式,即字符串保存在文件中

    其他语言要想使用Python的数据

    在文件中先取出字符串,然后通过json数据格式,转化为其他语言的数据类型

    PS:在json中,所有的字符串都是用双引号表示的

    ​ python中的元组比较特殊,若将其转换成json数据,内部会将元组--->列表

    怎么使用json?

    import json(导入json库)

    常用方法

    #列表类型
    #json.dumps(): 将python数据 ---》 json数据格式 ---》 字符串
    import json
    list1 = ['张全蛋', '王二狗']
    json_str = json.dumps(list1, ensure_ascii=False) #将ensurce_ascii改为False目的是可以看到中文,否则看到的为bytes类型
    json_str1 = json.dumps(list1)
    print(json_str)
    print(type(json_str))
    print(json_str1)
    print(type(json_str1))
    #结果为
    ["张全蛋", "王二狗"]
    <class 'str'>
    ["u5f20u5168u86cb", "u738bu4e8cu72d7"]
    print(type(json_str))
    <class 'str'>
    
    # json.loads()字符串 ----> json数据格式 ---》将python数据
    python_data = json.loads(json_str)
    print(python_data)
    print(type(python_data))
    #结果为
    ['张全蛋', '王二狗']
    <class 'list'>
    
    #字典类型
    dict1 = {
        'name': 'bing',
        'age': '21',
        'lived': 'shanghai'
    }
    a = json.dumps(dict1, ensure_ascii=False)
    print(a)
    print(type(a))
    
    b = json.loads(a)
    print(b)
    print(type(b))
    #结果为
    {"name": "bing", "age": "21", "lived": "shanghai"}
    <class 'str'>
    {'name': 'bing', 'age': '21', 'lived': 'shanghai'}
    <class 'dict'>
    
    #元组类型
    tuple1 = (1, 2, 3)
    c = json.dumps(tuple1, ensure_ascii=False)
    print(c)
    print(type(c))
    
    d = json.loads(c)
    print(d)
    print(type(d))
    #结果为
    [1, 2, 3]
    <class 'str'>
    [1, 2, 3]
    <class 'list'>
    
    #字符串
    str1 = 'bing'
    json_str = json.dumps(str1, ensure_ascii='False')
    print(json_str)
    print(type(json_str))
    
    json_str1 = json.loads(json_str)
    print(json_str1)
    print(type(json_str1))
    #结果为
    "bing"
    <class 'str'>
    bing
    <class 'str'>
    

    总结:

    1.在json中,所有的字符串都是用双引号表示的

    2.python中的元组比较特殊,若将其转换成json数据,通过json.load()读出来的时候为list类型

    3.集合是不能被序列化为json的

    4.json.dumps(‘可迭代对象’)是将python类型的文件转化为json的数据格式,最终都以字符串的形式写入文件;json.loads('字符串/字节/字节数组'),读出来的数据除了元组最后转化为列表外,其他都是自己本身的数据类型

    #注册用户,并以json的形式写入文件
    def register():
        while True:
            username = input('请输入您的用户名:').strip()
            if not username.isalpha():
                print('请输入英文字符')
                continue
            break
        while True:
            password = input('请输入您的密码:').strip()
            re_password = input('请确认您的密码:').strip()
            if not password == re_password:
                print('两次密码不一致,请重新输入:')
                continue
            break
        user_dir ={
            'name': username,
            'pwd': password
        }
        json_data = json.dumps(user_dir, ensure_ascii=False)
        with open('user.json', 'a+', encoding='utf-8')as f:
            f.write(json_data)
            f.write('
    ')
    
    
    register()
    
    #使用json.dump()在python数据类型转化后顺带写入文件
    import json
    user_dic = {
        'username': 'bing',
        'password': 123
    }
    f = open('user1.json', 'w', encoding='utf-8')
    json.dump(user_dic, f)
    f.close()
    #此处可以换个写法,效果一样
    with open('user2.json', 'w', encoding='utf-8')as f:
        json.dump(user_dic, f)
        
    #使用json.load()读出文件中的内容
    import json
    with open('user2.json', 'r', encoding='utf-8')as f:
    	user_dic = json.load(f)
        #user_dic = json.loads(f.read()) 该写法与上面的一样
        print(user_dic)
        print(type(user_dic))
    

    pickle模块

    pickle模块是一个python自带的序列化模块

    优点:可以支持python中的所有数据类型

    ​ 可以直接存’bytes'的数据,pickle存取速度更快

    缺点:只能支持python使用,不能跨平台

    import pickle
    set1 = {
        'name', 'age', 17
    }
    #写
    with open('aaa.pickle', 'wb')as f:
        pickle.dump(set1, f)
    #读
    with open('aaa.pickle', 'rb')as f:
        python_set = pickle.load(f)
        print(python_set)
        print(type(python_set))
    
  • 相关阅读:
    Bundles
    使用二进制协议 (附源码)
    河内之塔 算法
    什么是DCI
    C#利用ODP.NET往oracle中高效插入百万数据
    分析Sizzle引擎
    data格式加载图片
    jQuery获取checkbox选中项等操作及注意事项
    日期类型函数转换的特殊性
    QT中代码中与设计器中控件信号与SLOT连接(原来还可以这样连接)
  • 原文地址:https://www.cnblogs.com/a736659557/p/11894066.html
Copyright © 2011-2022 走看看