• python基础_json模块


    1.json模块可以序列化的数据、

    所有编程语言都能够识别的数据格式叫做json,是字符串
    如下类型可以转换成json字符串: int float bool str list tuple dict None

    ensure_ascii=False 显示中文
    sort_keys = True 对字典的键进行排序

     

    2.实际案例

    # ### 1.json用法
    import json
    # (1)dumps 和 loads 是一对, 序列化成字符串.
    # dumps序列化成字符串
    dic = {"name":"张三","age":18,"classroom":"python7","family":["老爸","老妈","妹妹"]}
    res = json.dumps(dic,ensure_ascii=False,sort_keys=True)
    print(res,type(res))
    
    # loads反序列化成原来的数据类型
    dic = json.loads(res)
    print(dic,type(dic))
    
    # (2) dump 和 load 是一对,针对于文件操作
    dic = {"name":"张三","age":18,"classroom":"python7","family":["老爸","老妈","妹妹"]}
    # dump(要转化的数据,文件对象,关键字实参...)
    with open("ceshi1.json",mode="w",encoding="utf-8") as fp:
        json.dump(dic,fp,ensure_ascii=False)
    
    # load(文件对象)
    with open("ceshi1.json",mode="r",encoding="utf-8") as fp:
        dic = json.load(fp)
    print(dic,type(dic))

    3.json数据连续dump和load操作

    # (1)json
    """
    可以连续dump , 不可以连续load
    load 特征是一次性把所有的内容都取出来变成一个完整的字典;
    所以如果是多个字典不能够转化; 
    
    # 解决方式:
    loads 可以 配合遍历文件对象,一行一行读取内容,在通过loads来转换成原来的数据类型
    """
    dic1 = {"a":1,"b":2}
    dic2 = {"c":3,"d":4}
    with open("ceshi2.json",mode="w",encoding="utf-8") as fp:
        json.dump(dic1,fp)
        fp.write("
    ")
        json.dump(dic2,fp)
        fp.write("
    ")
        
    # 文件对象是迭代器,可以遍历;
    from collections import Iterator,Iterable
    res = isinstance(fp,Iterator)
    print(res)
    
    # 用loads 来解决load存在的弊端;
    with open("ceshi2.json",mode="r",encoding="utf-8") as fp:
        for i in fp:
            # print(i,type(i))
            dic = json.loads(i)
            print(dic,type(dic))

    4.pickle连续dump和load操作

    # (2)pickle
    print("<===>")
    import pickle
    """
    可以连续dump ,也可以连续load
    """
    dic1 = {"a":1,"b":2}
    dic2 = {"c":3,"d":4}
    with open("ceshi3.pkl",mode="wb") as fp:
        pickle.dump(dic1,fp)
        pickle.dump(dic2,fp)
        
    # 方法一
    with open("ceshi3.pkl",mode="rb") as fp:
        dic1 = pickle.load(fp)
        dic2 = pickle.load(fp)
        
    print(dic1,type(dic1))
    print(dic2,type(dic2))
    
    # 方法二
    try:
        with open("ceshi3.pkl",mode="rb") as fp:
            while True:
                dic = pickle.load(fp)
                print(dic)
    except:
        pass
  • 相关阅读:
    js 整站模式窗口打开
    WebDev.WebServer 学习
    AjaxPro.2.dll基本使用
    jQuery.get(url,[data],[callback])
    ASP.NET CheckBoxList复选框
    Win7开发系列: windows服务操作基础
    .NET Remoting开发系列:(三) Remoting服务发布方式
    mysql 视图操作和存储过程
    Flash Lite1.1错误代码表
    myeclipse svn 清除缓存用户和密码
  • 原文地址:https://www.cnblogs.com/jalen-123/p/13173782.html
Copyright © 2020-2023  润新知