女生节也要好好更新^_^
有关python与json编码请查看上篇:http://www.cnblogs.com/hazelrunner/p/8444744.html
下面来区分,用post请求方法传json的两种方法:
- 传json参数(方法中直接转json)
# coding:utf-8
import requests
import json
payload = {"username": "dingding",
"python": 123456,
"requests": True}
url = "http://music.163.com/"
# 第一种直接传json参数(推荐这种)
r1 = requests.post(url, json=payload) # json参数直接自动转json了
print(r1.text)
2.传data参数(需先转json)
# coding:utf-8
import requests
import json
payload = {"username": "dingding",
"python": 123456,
"requests": True}
url = "http://music.163.com/"
# 第二种传data参数,需要转json
r2 = requests.post(url, data=json.dumps(payload)) # 传data参数就需要转json
print(r2.text)
----------------------------------------------------------------------------------------------------
json解析方法:
result1 = r1.content #字节输出
print(type(result1)) # 这里是str类型<type 'str'>
print(result1) #输出结果{"success":true}
result2 = r1.json() #解析json
print(type(result2)) # 这里是dict类型<type 'dict'>
print(result2) #输出结果{u'success': True}
print(result2['success']) # 取出dict里sucess字段