今天在完善ccnubox_monitor时发现需要利用返回的数据.所以学了一下Python里怎么解析json数据.

因为需要先添加一节课,然后拿到这节课的id,之后用在删除这节课的api中,所以我们就需要先拿到添加这节课时返回的json数据里面的id.

具体代码如下(一些密码之类的删去了)

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
#coding:utf-8
import requests
import json
from flask import jsonify
login_header = {'login':'header'}
#添加课程
post_data={
"course":"test",
"teacher":"test",
"weeks":"1,2,3,4",
"day":"星期1",
"start":"1",
"during":"1",
"place":"9-11",
"remind":False
}
resp07=requests.post("https://ccnubox.addclass.url",
json = post_data,
headers = login_header)
statu07 = resp07.status_code
#print resp07.text
#print type(resp07.text)
json_data = resp07.json()
#print json_data
#print type(json_data)
global class_id
class_id = json_data["id"]
#print class_id
#删除课程 ID 为课程ID
resp09 = requests.delete("https://ccnubox.deleteclass.url/"+str(class_id)+"/",
headers = login_info_header )
statu09=resp09.status_code
print statu09

首先,利用requests的post方法发送一个添加课程的请求.
这时候我们print 一下他的text,发现是
{"id": 814}
然后print 一下他的type(resp07.text),发现是
<type 'unicode'>
上网查阅之后,得知利用 requests 所得到的response是Response类,他有一个方法是 json
所以,我们让 json_data = resp.json() .
此时我以为resp.json()得到的还是json类型,然后想把它转化成python中的dict类型.但是怎么都弄不好,后来type(resp.json())发现返回的是:
<type 'dict'>
也就是说,resp.json()就直接将json数据变成了dict类型,所以我们此时就可以直接用键值对来拿里面的东西了:class_id = json_data["id"] .
所以我们就可以在删除里面用class_id了:str(class_id)
大概就是这样.

本文地址: http://Humbertzhang.github.io/2017/05/15/Flask下解析requests返回的json数据/