python请求包中data和json参数的区别

新手上路,请多包涵

python Requests包中的data和json参数有什么区别?

文档 中不清楚

这段代码:

 import requests
import json
d = {'a': 1}
response = requests.post(url, data=json.dumps(d))

请注意,我们在这里将 dict 转换为 JSON ☝️!

做任何不同于:

 import requests
import json
d = {'a': 1}
response = requests.post(url, json=d)

如果是这样,什么?后者是否自动将标头中的 content-type 设置为 application/json

原文由 user1507844 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 418
2 个回答

为了回答我自己的问题,我上面的两个例子似乎做了同样的事情,并且使用 json 参数确实将标头中的 --- 设置为 content-type application/json .在我上面使用 data 参数的第一个示例中,标头中的 content-type 需要手动设置。

原文由 user1507844 发布,翻译遵循 CC BY-SA 3.0 许可协议

截至 2021 年 12 月,关于使用 requests文档 datajson 的区别现在非常清楚。

(我们对此做出了小小的贡献—— 我的 PR 和您的赞成票证实这曾经是一个问题。谢谢!)。

PS 这不回答 OP 问题,但如果第一段代码会有点不同:

 import requests
import json
d = {'a': 1}
response = requests.post(url, data=d)

(请注意, dict d 在此处转换为 JSON 字符串!)

如果第二个代码相同(为了完整性而复制它):

 import requests
import json
d = {'a': 1}
response = requests.post(url, json=d)

……那么结果就大不一样了。

第一个代码将生成一个内容类型设置为 application/x-www-form-urlencoded 的请求以及这种格式的数据,因此: "a=1"

第二个代码将生成内容类型设置为 application/json 的请求,实际上是这种格式的数据,所以 {"a": 1} 一个 JSON 字符串。

原文由 Greg Dubicki 发布,翻译遵循 CC BY-SA 4.0 许可协议

推荐问题