赞
踩
json.dumps的功能是将字典类型转换为json格式的字符串类型,爬虫领域经常用到该函数,要配合请求头’Content-Type’: 'application/json;charset=utf-8’进行使用。
import json
data = {'token':'e5dads5 3455s2','verify':True,'content':'中文'}
data_json = json.dumps(data)
print(data_json)
#输出:{"token": "e5dads5 3455s2", "verify": true, "content": "\u4e2d\u6587"}
def dumps(obj, *,
skipkeys=False, # skipkeys=True 为键按a~z进行排序
ensure_ascii=True, # ensure_ascii=False 默认的ASCLL码用中文显示
check_circular=True,
allow_nan=True,
cls=None,
indent=None,
separators=None, # separators=(',',':') 将,:后面的空格去掉
default=None,
sort_keys=False,
**kw):
pass
1、去掉,:后面的空格
import json
data = {'token':'e5dads5 3455s2','verify':True,'content':'中文'}
data_json = json.dumps(data,separators=(',',':'))
print(data_json)
#输出:{"token":"e5dads5 3455s2","verify":true,"content":"\u4e2d\u6587"}
# 不建议使用以下方法
data_json = json.dumps(data).replace(' ','')
#输出:{"token":"e5dads53455s2","verify":true,"content":"\u4e2d\u6587"}
# 你会发现少点了什么
2、正常显示中文
import json
data = {'token':'e5dads5 3455s2','verify':True,'content':'中文'}
data_json = json.dumps(data,ensure_ascii=False)
print(data_json)
#输出:{"token": "e5dads5 3455s2", "verify": true, "content": "中文"}
import requests
import json
url = 'https://www.baidu.com/?'
data = {"id": "001","key": "123"}
params = {
'sx': '2s',
'appid': 'as',
'data': json.dumps(data,separators=(',',':')),
}
res = requests.get(url=url, params=params)
print(res.text)
import requests
import json
url = 'https://baidu.com/'
headers = {
'content-type': 'application/json;charset=utf-8'
}
data = {"key1":"value1","key2":"value2"}
res = requests.post(url=url,headers=headers,data=json.dumps(data,separators=(',',':')))
print(res.text)
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。