• json和文件操作


    json数据

    json

    json是一种通用的数据格式,可以用于不同的编程语言之间的数据交流。

    json相对于xml更小更轻,传输速度更快,xml相对json更安全。

    json数据

    json数据格式的要求:一个json有且只有一个数据;唯一的这个数据必须是json支持的类型的数据。

    json支持类型

    1. 数字:包括整数和小数,表示的时候直接表示。
    2. 字符串:用双引号引起来的数据,“abc”、“小明”、“abc\n”(json文件中不支持单引号)
    3. 布尔:只有true和false两个值
    4. 空值:null
    5. 数组:相当于Python的列表:[数据1,数据2,数据3,…]
    6. 字典:相当于Python的字典,但是json中的键只能是字符串:{键1:值1,键2:值2,…}

    Python数据和json数据之间的相互转换

    json转Python

    json --> Python
    数字 数字
    字符串 字符串(双引号变单引号)
    布尔 布尔(true ->True、false ->False)
    空值 空值(null ->None)
    数组 列表
    字典 字典

    对应的函数:json.loads(json格式的字符串) - 将json格式字符串对应的json数据转换Python数据

    json格式字符串指的是内容是json数据的字符串

    import json
    
    content = open('data.json', encoding='utf-8').read()
    reslut = json.loads(content)  # {'name': '小明', 'age': 10, 'gender': '男', 'isMarrade': False}
    reslut1 = json.loads('"abc"')  # abc
    reslut2 = json.loads('[100,"小明",null,true]')  # [100, '小明', None, True]
    print(reslut, reslut1, reslut2)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    Python转json

    python --> json
    int、float 数字
    str 字符串(单引号会变成双引号)
    bool True -> true、False -> false
    None null
    列表、元组 数组
    字典 字典

    json.dumps(Python数据) - 将指定Python数据转换成对应的json格式字符串

    json.dumps(100)             # '100'
    json.dumps('abc')           # '"abc"'
    json.dumps(True)            # 'true'
    
    • 1
    • 2
    • 3

    案例:从网页接口中解析数据获取所有英雄的名字

    # 1.获取json数据(从文件中读出来、直接做网络请求)
    import requests
    
    resp = requests.get('https://game.gtimg.cn/images/lol/act/img/js/heroList/hero_list.js?ts=2766570')
    content = resp.text
    print(type(content), content)
    # 2.json解析(将json数据转换成对应的Python数据)
    result = json.loads(content)
    for i in result['hero']:
        print(i['name'], i['title'])
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    json的实际应用

    案例:学生管理系统添加学生

    """
    =========添加学生==========
    请输入学生姓名:stu1
    请输入学生的年龄:19
    请输入学生的手机号:110
    请输入学生的专业:电子信息
    请输入学生的籍贯:重庆
    添加成功!
    ❤️1. 继续
    ❤️2. 退出
    请选择:1
    
    =========添加学生==========
    请输入学生姓名:stu2
    请输入学生的年龄22
    请输入学生的手机号:3332
    请输入学生的专业:电子信息
    请输入学生的籍贯:重庆
    添加成功!
    ❤️1. 继续
    ❤️2. 退出
    请选择:1
    
    ....
    
    =========添加学生==========
    请输入学生姓名:stu2
    请输入学生的年龄:22
    请输入学生的手机号:3332
    请输入学生的专业:电子信息
    请输入学生的籍贯:重庆
    添加成功!
    ❤️1. 继续
    ❤️2. 退出
    请选择:2
    (显示已经添加的所有的学生信息!)
    (程序结束)
    
    """
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    1. 已经添加过的所有学生需要持久化

    2. 文件内容格式:

      [  
          {"name": "小明", "age": 18, "major":"电子信息", "address": "成都"},
          ...
      ]
      
      • 1
      • 2
      • 3
      • 4
    import json
    
    
    def add_student():
        while True:
            # 1. 输入学生信息
            print('=========添加学生==========')
            name = input('请输入学生姓名:')
            age = input('请输入学生的年龄:')
            tel = input('请输入学生的电话:')
            major = input('请输入学生的专业:')
            address = input('请输入学生的籍贯:')
    
            # 2. 保存学生信息
            content = open('files/students.txt', encoding='utf-8').read()  # '[]'
            # content = content.read()
            all_students = json.loads(content)  # type: list
    
            # [{}]
            all_students.append({'name': name, 'age': age, 'tel': tel, 'major': major, 'address': address})
            open('files/students.txt', 'w', encoding='utf-8').write(json.dumps(all_students))
    
            print('添加成功!')
            # 3. 提示继续或者退出
            print('❤️1. 继续')
            print('❤️2. 退出')
            value = input('请选择:')
            if value == '1':
                pass
            else:
                # 打印已经添加过的所有的学生信息
                print(all_students)
                break
    
    
    if __name__ == '__main__':
        # add_student()
    
        # 统计电子专业学生的人数:
        all_student = json.loads(open('files/students.txt', encoding='utf-8').read())
        count = 0
        for x in all_student:
            if x['major'] == '电子':
                count += 1
        print(count)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
  • 相关阅读:
    Allegro输出DXF文件操作指导
    华为云大数据BI 为中小型企业智慧运营保驾护航
    Python模块:hashlib模块教程
    Linux环境下安装docker环境(亲测无坑)
    Web3D水厂:数字孪生智慧水务三维WebGL可视化管理系统
    如何使用ChatGPT创建一份优质简历
    如何提高API接口的性能和设计安全可靠的API
    使用jmeter进行接口测试
    【毕业设计】深度学习手势识别系统 - yolo python opencv 机器视觉
    发送短信验证码的倒计时一直停留在60秒,没有开始倒计时
  • 原文地址:https://blog.csdn.net/qq_56630044/article/details/126234244