python requests data和json参数的区别

在通过request.post()进行POST请求时,传入报文的参数有两个,一个是data,一个是json data与json 两者 分别由两种类型,一种是 str类型 一种是 dict 字典类型

那么两者之间有什么区别呢

不管是json还是str 还是dict,如果没有指定特定的请求头 headers中你的content-type,默认为 application/jsondata 为 dict 时,如果不指定content-type ,默认为普通表单的形式,比如not_checkout=1&spm=1000.2115.3001.4503&articleId=127684488这就是普通表单的形式,简单get请求 ,默认为application/x-www-form-urlencodeddata 为 str时,如果不指定acontent-type more默认为text/plainjson为 dict 时,如果不指定contenct-type 默认为application/jsonjson为 str 时,如果不指定contenct-type 默认为application/json用data参数提交数据时,request.body 的内容为a=1&b=2的形式,而用json参数提交数据时,{“a”:1,"b":2}的这种 key-value的形式

下面贴上具体代码,好好理解一下

>>> r = requests.post('http://httpbin.org/post', json = {'key':'value'})

>>> r.json()

{'args': {}, 'data': '{"key": "value"}', 'files': {}, 'form': {}, 'headers': {'Accept': '*/*', 'Accept-Encoding': 'gzip, deflate', 'Content-Length': '16', 'Content-Type': 'application/json', 'Host': 'httpbin.org', 'User-Agent': 'python-requests/2.23.0', 'X-Amzn-Trace-Id': 'Root=1-5ecc83a5-6972ba8590410bc2c36d42df'}, 'json': {'key': 'value'}, 'origin': '61.148.199.18', 'url': 'http://httpbin.org/post'}

>>> r = requests.post('http://httpbin.org/post', json = json.dumps({'key':'value'}))

>>> r.json()

{'args': {}, 'data': '"{\\"key\\": \\"value\\"}"', 'files': {}, 'form': {}, 'headers': {'Accept': '*/*', 'Accept-Encoding': 'gzip, deflate', 'Content-Length': '22', 'Content-Type': 'application/json', 'Host': 'httpbin.org', 'User-Agent': 'python-requests/2.23.0', 'X-Amzn-Trace-Id': 'Root=1-5ecc83b3-fd9620d07da4d72c64bb8b04'}, 'json': '{"key": "value"}', 'origin': '61.148.199.18', 'url': 'http://httpbin.org/post'}

>>> r = requests.post('http://httpbin.org/post', data = json.dumps({'key':'value'}))

>>> r.json()

{'args': {}, 'data': '{"key": "value"}', 'files': {}, 'form': {}, 'headers': {'Accept': '*/*', 'Accept-Encoding': 'gzip, deflate', 'Content-Length': '16', 'Host': 'httpbin.org', 'User-Agent': 'python-requests/2.23.0', 'X-Amzn-Trace-Id': 'Root=1-5ecc83c1-c5d88e82526fc52b94a51f00'}, 'json': {'key': 'value'}, 'origin': '61.148.199.18', 'url': 'http://httpbin.org/post'}

>>> r = requests.post('http://httpbin.org/post', data = {'key':'value'})

>>> r.json()

{'args': {}, 'data': '', 'files': {}, 'form': {'key': 'value'}, 'headers': {'Accept': '*/*', 'Accept-Encoding': 'gzip, deflate', 'Content-Length': '9', 'Content-Type': 'application/x-www-form-urlencoded', 'Host': 'httpbin.org', 'User-Agent': 'python-requests/2.23.0', 'X-Amzn-Trace-Id': 'Root=1-5ecc83d0-09f85bff232d89cec4e5bdfb'}, 'json': None, 'origin': '61.148.199.18', 'url': 'http://httpbin.org/post'}

  

其中,介绍一下序列号和反序列化

json.dumps(data) 序列化 把字典格式的数据转换成str格式

json.loads(data) 反序列化 把str格式转换成字典格式

相关文章

评论可见,请评论后查看内容,谢谢!!!
 您阅读本篇文章共花了: