day13 Json和异常处理

2019-01-09  本文已影响0人  挽风style

Json

  1. 什么是json数据
    json是一种具有特定语法的数据格式

  2. json数据的语法
    一个json数据有且只有一个数据,这个数据的数据类型必须是json支持的数据类型

  3. json支持的数据类型

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

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

b.dumps(对象) - 将指定的对象转换成json数据,以字符串的形式返回(这儿的对象指的就是python数据)

注意:
返回值是字符串,并且字符串的内容是json数据
集合不能转换成json数据

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

读json文件

    with open('date.json', encoding='utf-8') as f:
        result = json.load(f)  # 相当于 result = json.loads(f.read())
        print(type(result), result)

    all_student = [
        {'name': 'xiaohu', 'age': 21, 'tel': 1213432},
        {'name': 'gulk', 'age': 25, 'tel': 13543432},
        {'name': 'sary', 'age': 18, 'tel': 121356532},
        {'name': 'scout', 'age': 23, 'tel': 144413432}
    ]
    with open('student.json', 'w', encoding='utf-8') as f:
        json.dump(all_student, f)  # f.write(json.dumps(all_student))

python转json

    result = json.dumps(100.2)
    print(result, type(result))

    result = json.dumps('abc')
    print(result, type(result))

    result = json.dumps(True)
    print(result, type(result))

    result = json.dumps([10, 'abc', True, None])
    print(result, type(result))

    result = json.dumps({'age': 10, 'name': 'abc', 'good': True})
    print(result, type(result))

json转python

    # 将json中的字符串转换成python数据
    content = json.loads('"abc"')
    print(content, type(content))

    # 将json中的数字转换成python数据
    content = json.loads('123')
    print(content, type(content))

    # 将json中的数字转换成python数据
    content = json.loads('{"name": "张三", "age": 34, "sex": null, "good": true}')
    print(content, type(content))

练习:用一个列表保存多个学生的信息,写函数向这个列表添加学生(姓名、电话、成绩),要求之前添加过的学生,下次运行程序的时候还在

import json


def add_student(all_student):
    name = input('姓名:')
    tel = int(input('电话:'))
    score = float(input('成绩:'))
    all_student.append({'name': name, 'tel': tel, 'score': score})
    with open('stu.json', 'w', encoding='utf-8') as f:
        json.dump(all_student, f)


def main():
    with open('stu.json', 'r', encoding='utf-8') as f:
        all_student = json.load(f)
    add_student(all_student)
    
    
if __name__ == '__main__':
    main()

网络请求

python中的数据请求(http请求),是第三方库requests来提供的

  1. requests第三方库的使用
    get/post方法都是发送请求获取接口提供的数据
1. 发送数据,并且获取返回的数据
    # 服务器返回的数据叫响应

    # response = requests.get('https://www.apiopen.top/meituApi?page=1')
    response = requests.get('https://www.apiopen.top/meituApi', {'page': 1})
    print(response)
2. 从响应中获取数据
    a.获取json数据
    content_json = response.json()  # 会自动将json数据转换成python对应的数据
    print(type(content_json))

    b.获取字符串数据
    content_text = response.text
    print(type(content_text))
    print(content_text)

    c.获取二进制数据(原始数据)
    content_bytes = response.content
    print(type(content_bytes))
    print(content_bytes)

    下载图片
    response2 = requests.get('http://img0.imgtn.bdimg.com/it/u=2413964795,123851941&fm=26&gp=0.jpg')
    with open('q1.jpg', 'wb') as f:
        f.write(response2.content)
        print(response2.content)

异常处理

  1. 异常捕获 - 让本该报错的代码不报错
  1. 异常捕获语法

执行过程: 执行代码段1,如果代码段1中出现异常,程序不崩溃,直接执行代码段2
如果代码段1中没有出现异常,不执行代码段2而是直接执行后面的其他语句

def method1():
    print('=========1.try-except========')
    try:
        number = int(input('请输入一个数字:'))
        print(number)
    except:
        print('出现异常,输入有误!')
def method3():
    try:
        print('========2.try-except==========')
        print({'a': 2}['b'])
        print([1, 2, 3][4])
    except (IndexError, KeyError):
        print('出现异常')
def method4():
    try:
        print('========3.try-except==========')
        with open('abc.txt', 'r') as f:
            print(f.read())
        print({'a': 2}['b'])
        print([1, 2, 3][4])
    except IndexError:
        print('下标超出范围')
    except FileNotFoundError:
        print('文件不存在')
    except KeyError:
        print('键不存在')
  1. 抛出异常 - 主动让程序崩溃
def func1(age: int):
    if age > 18:
        raise ValueError
    print(age)

练习: 输入数字,如果输入有误就继续输入,直到输入正确为止
例如:输入数字: 12a 输入有误,继续输入!

def method2():
    while True:
        try:
            number = int(input('请输入一个数字:'))
            print('输入正确', number)
            break
        except:
            print('输入有误,继续输入!')
上一篇 下一篇

猜你喜欢

热点阅读