zoukankan      html  css  js  c++  java
  • Python之json模块

    一、序列化需求

    假如有一个其它语言编写很大的字典,通过网络传输协作开发,使用前需要转换成字典。

    dic = {'name': 'lin', 'age': 25, 'sex': ''}
    ret = str(dic).encode('utf-8')                            # 传输过来之后是byte类型
    
    ret1 = ret.decode('utf-8')
    print(ret1, type(ret1))                                   # 通过此方法,只能取到字符串类型,可以使用eval()方法,但是不建议。
    
    ----------------------执行结果-------------------------
    {'name': 'lin', 'age': 25, 'sex': ''} <class 'str'>
    ------------------------------------------------------

    二、使用json模块,适用于所有语言

    2.1  dumps和loads主要用于网络传输;将重要的数据变成可以传输的,并且得到后能够反解出来。

    import json
    dic = {'name': 'lin', 'age': 25, 'sex': ''}
    ret = json.dumps(dic)
    print(ret, type(ret))
    
    ----------------------执行结果-------------------------
    {"name": "lin", "age": 25, "sex": "u7537"} <class 'str'>   # 序列化就是变成一个特殊的字符串
    ------------------------------------------------------
    
    ret = json.dumps(dic, ensure_ascii=False)                   # 设置ensure_ascii
    print(ret, type(ret))
    ----------------------执行结果-------------------------
    {"name": "lin", "age": 25, "sex": ""} <class 'str'>
    ------------------------------------------------------
    
    respon = json.loads(ret)                                    # 使用loads进行反序列化,反解成原来的类型
    print(respon, type(respon))
    print(respon.get('name'))
    ----------------------执行结果-------------------------
    {'name': 'lin', 'age': 25, 'sex': ''} <class 'dict'>
    lin
    ------------------------------------------------------

    2.2 dump和load用于写入文件操作

    dic = {'Request_Server_Name': 'www.abc.com', 'Request_Server_Host': '1.1.1.1', 'Request_Server_Port': '443',
            'Forward_Real_WebServer': '10.10.10.1', 'Request_Real_Client': '2.2.2.2', 'Requests_number': 1,
            'Request_Size': 1024, 'Requst_Return_Status_Code': 200, 'Request_Mothod': 'GET /'
           }
    
    with open('access.log', 'w') as f:
        json.dump(dic, f)                                        # dump方法接收一个文件句柄,直接将字典转换成json字符串写入文件
    
    ------------------------------------------------------
    with open('access.log', mode='r') as f:
        dic2 = json.load(f)                                      # load方法读取文件句柄,直接将文件中的json字符串转换成数据结构返回
        print(type(dic2))
        print(dic2.get('Request_Size'))
    ----------------------执行结果-------------------------
    <class 'dict'> 1024
    ------------------------------------------------------
  • 相关阅读:
    GitLab 介绍
    git 标签
    git 分支
    git 仓库 撤销提交 git reset and 查看本地历史操作 git reflog
    git 仓库 回退功能 git checkout
    python 并发编程 多进程 练习题
    git 命令 查看历史提交 git log
    git 命令 git diff 查看 Git 区域文件的具体改动
    POJ 2608
    POJ 2610
  • 原文地址:https://www.cnblogs.com/cyleon/p/10492408.html
Copyright © 2011-2022 走看看