zoukankan      html  css  js  c++  java
  • 函数和常用模块【day06】:json模块(十一)

    本节内容

    1、dumps序列化和loads反序列化

    2、dump序列化和load反序列化

    3、序列函数

    1、dumps序列化和loads反序列化

    dumps()序列化

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    import  json   #导入json模块
     
    info = {
        'name':"zhangqigao",
        "age":22
    }
     
    with open("test.txt","w") as f:  #以普通模式写入
        data = json.dumps(info) #把内存对象转为字符串
        f.write(data)   #写到文件中
     
    #text.txt文件中的内容
    {"name""zhangqigao""age"22}

    loads()反序列化

    1
    2
    3
    4
    5
    6
    7
    8
    9
    import json
     
    with open("test.txt","r") as f:  #以普通模式读
        data = json.loads(f.read())   #用loads反序列化
     
    print(data.get("age"))
     
    #输出
    22

    2、dump序列化和load反序列化

    dump()序列化

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    import  json
     
    info = {
        'name':"zhangqigao",
        "age":22
    }
     
    with open("test.txt","w") as f:   #文件以写的方式打开
        json.dump(info,f)    #第1个参数是内存的数据对象 ,第2个参数是文件句柄
     
    #text.txt文件中的内容
    {"name""zhangqigao""age"22}

     load()反序列化

    1
    2
    3
    4
    5
    6
    7
    8
    9
    import json
     
    with open("test.txt","r") as f:   #以读的方式打开文件
        data = json.load(f)  #输入文件对象
     
    print(data.get("age"))
     
    #输出
    22

    3、序列化函数

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    import  json
     
    def sayhi(name):  #函数
        print("name:",name)
     
    info = {
        'name':"zhangqigao",
        "age":22,
        "func":sayhi    #引用sayhi函数名
    }
     
    with open("test.txt","w") as f:
        json.dump(info,f)   #序列化info数据对象
     
    #输出
     File "D:PythonPython35libjsonencoder.py", line 403in _iterencode_dict
        yield from chunks
      File "D:PythonPython35libjsonencoder.py", line 436in _iterencode
        = _default(o)
      File "D:PythonPython35libjsonencoder.py", line 179in default
        raise TypeError(repr(o) + " is not JSON serializable")
    TypeError: <function sayhi at 0x00000000006DD510is not JSON serializable  #不支持jsom序列化

    小结:

    1. dumps和loads是成对使用的,dump和load是成对使用的。
    2. dumps和loads由于序列化的是内容,所以后面要加s,但是dump和load序列化的内容是对象,所以单数。
    3. json只能处理简单的数据类型,例如:字典、列表、字符串等,不能处理函数等复杂的数据类型。
    4. json是所有语言通用的,所有语言都支持json,如果我们需要python跟其他语言进行数据交互,那么就用json格式。
  • 相关阅读:
    leetcode_question_67 Add Binary
    几种常用控件的使用方法
    JavaBean讲解 规范
    [置顶] JDK-CountDownLatch-实例、源码和模拟实现
    恋人分手后需要做的不是挽回而是二次吸引
    leetcode_question_70 Climbing Stairs
    偶然碰到的Win7 64位下CHM 的问题解决
    FTP中各文件目录的说明
    深入理解line-height与vertical-align(1)
    行内元素和块级元素
  • 原文地址:https://www.cnblogs.com/luoahong/p/7196089.html
Copyright © 2011-2022 走看看