美文网首页
19-01-09json数据

19-01-09json数据

作者: one丨 | 来源:发表于2019-01-09 19:32 被阅读0次

    json

    1.什么是json数据

    • json是一种具有特定语法的数据格式

    2.json数据的语法

    • 一个json数据有且只有一个数据, 这个数据的数据类型必须是json支持的数据类型

    3.json支持的数据类型

    • a.数字类型: 包含所有的数字,包括整数、小数;例如: 100, 12.5, -3.14
      注意:(1)整数前面不能加'+'
      (2)支持科学计数法: 3e2
    • b.字符串: 使用双引号括起来的数据; 例如:"abc", "abc123,!"
    • c.布尔: 只有true和false两个值
    • d.数组: 相当于python的列表,用[]括起来,多个元素用逗号隔开;例如: [100, "abc", [1, 2]]
    • e.字典: 相当于python的字典, 用{}括起来,多个键值对用逗号隔开, 例如:{"a": 10, "b": 20, "c": [1, 3]}
    • f.空值: null,相当于python中的None

    4.python处理json数据

    python中提供了json模块,专门用来处理json数据

    1, 将json数据转换成python数据(通过爬虫获取到别人提供的json数据,在python中处理)

    • a.转换方式
      json --> python
      数字 int/float
      字符串 str, 可能双引号会变成单引号
      布尔 bool, 会将json中的true/false转换成True/False
      数组 list
      字典 dict
      空值(null) None

    • b.loads方法
      loads(字符串, encoding='utf-8') - 将字符串中的json数据转换成对应的python数据
      !!!!!!!!注意: 这儿的字符串中!!!内容!!!!必须json数据

    2,将python数据转换成json数据(python写后台接口将数据提供给客户端)

    • a.转换方式
      python ---> json
      int/float 数字
      str 字符串, 单引号会变成双引号
      bool True->true; False->false
      list/tuple 数组
      dict 字典
      None null
    • b.dumps(对象) - 将指定的对象转换成json数据, 以字符串的形式返回
      这儿的对象指的就是python数据
      注意: 返回值是字符串,并且字符串的!!!!内容!!!!是json数据

    5.json文件处理

    严格来说,json文件是文件内容是json数据的文件

    • load(文件对象) - 将指定文件中的内容读出来,并且转换成python对应的数据。
      注意:这儿的文件对象对应的文件必须是json文件

    • dump(对象, 文件对象) - 将指定对象转换成内容是json格式的字符串,然后写入指定的文件中
      注意:这儿的对象对应的类型必须是能够转换成json的数据类型

    import json(导入json模块)

    def main():(格式,方便整段代码以后带入其他代码内)

    ======3.读json文件========

    with open('data.json', encoding='utf-8') as f:
        result = json.load(f)   # 相当于 result = json.loads(f.read())
        print(type(result), result['msg'])
    
    all_student = [
        {'name': '小明', 'age': 12, 'tel': '1237736'},
        {'name': 'yuting', 'age': 18, 'tel': '23333'},
        {'name': 'Luffy', 'age': 20, 'tel': None},
        {'name': 'zuoLuo', 'age': 30, 'tel': '923736'},
    ]
    with open('student.json', 'w', encoding='utf-8') as f:
        json.dump(all_student, f)  # 相当于 f.write(json.dumps(all_student))
    
    print(' ===============2.python转json===============')
    result = json.dumps(100.23)
    print(type(result), result)    # '100.23'
    
    result = json.dumps('abc')
    print(type(result), result)  # '"abc"'
    
    result = json.dumps(True)
    print(type(result), result)  # 'true'
    
    result = json.dumps([10, 'abc', True, None])
    print(type(result), result)  # '[10, "abc", true, null]'
    
    result = json.dumps((10, 'abc', True, None))
    print(type(result), result)  # '[10, "abc", true, null]'
    
    result = json.dumps({'a': 10, 'b': 'abc', 'c': True, 'd': None})
    print(type(result), result)  # '{"a": 10, "b": "abc", "c": true, "d": null}'
    
    # 集合不能转换成json数据
    # result = json.dumps({10, 'abc', True, None})
    # print(type(result), result)  # '[10, "abc", true, null]'
    
    
    # ===============1.json转python===============
    print('===========================')
    # 将json中的字符串转换成python数据
    content = json.loads('"abc"', encoding='utf-8')
    print(content, type(content))   # abc <class 'str'>
    
    # 将json中的数字转换成python数据
    content = json.loads('100', encoding='utf-8')
    print(content, type(content))
    
    # 将json中的字典转换成python数据
    message = '{"name": "张三", "age": 18, "sex": null, "marry": true}'
    content = json.loads(message, encoding='utf-8')
    print(content, type(content))
    print(content['name'])
    
    # 练习1
    with open('data.json', encoding='utf-8') as f:
        info = f.read()
        # print(type(info), info)
        dict1 = json.loads(info, encoding='utf-8')
        for item in dict1['data']:
            print(item['url'])
    
    image.png
    • 用一个列表保存多个学生的信息.写函数向这个列表
    • 中添加学生(姓名、年龄、成绩)。
    • 要求之前添加过的学生,下次运行程序的时候还在
    all_student = 空
    add_student()
    import json
    
    
    def add_student(list1: list):
        name = input('姓名:')
        age = int(input('年龄:'))
        score = float(input('成绩:'))
        list1.append({'name': name, 'age': age, 'score': score})
    
    
    def main():
        # 获取数据
        # all_student = []
        with open('allStudent.json', encoding='utf-8') as f:
            all_student = json.load(f)
            # all_student = [{}, {}]
    
        add_student(all_student)
        add_student(all_student)
        # all_student = [{}, {}, {}, {}]
    
        # 更新数据
        with open('allStudent.json', 'w', encoding='utf-8') as f:
            json.dump(all_student, f)
    
        print(all_student)
    
    
    if __name__ == '__main__':
        main()
    

    相关文章

      网友评论

          本文标题:19-01-09json数据

          本文链接:https://www.haomeiwen.com/subject/zlzgrqtx.html