【问题标题】:How to convert request.data to dict? [duplicate]如何将 request.data 转换为 dict? [复制]
【发布时间】:2018-08-02 16:45:18
【问题描述】:

我尝试使用这一行(请求库)POST 请求从客户端获取 JSON 数据:

request.data

如何将其转换为字典?

有效:

response_data = request.get_json()

但是如何将其转换为 dict?

【问题讨论】:

  • 试试request.json(),假设request是response的名字...
  • 您能否提供一些您正在尝试做的细节。
  • 如果你的响应文本是 json 使用 dict_data = json.loads(json_str)
  • 我试过这个:`response_data = request.json() print(response_data)` 得到:`object is not callable"`

标签: python json python-3.x python-requests


【解决方案1】:

编辑:对于发布请求:

import requests
import json
url = "https://jsonplaceholder.typicode.com/posts/"

payload = {
    "userId": 10,
    "id": 901,
    "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
    "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
 }
headers = {
    'content-type': "application/json",
    'cache-control': "no-cache",
    'postman-token': "c71c65a6-07f4-a2a4-a6f8-dca3fd706a7a"
    }

response = requests.request("POST", url, data=json.dumps(payload), headers=headers)

print(type(response.json()))

类'dict'


你可以这样使用:

import requests

url = "https://api.icndb.com/jokes/random"

headers = {
    'cache-control': "no-cache",
    'postman-token': "77047c8b-caed-2b2c-ab33-dbddf52a7a9f"
    }

response = requests.request("GET", url, headers=headers)

print(type(response.json()))

类'dict'

【讨论】:

  • 我发送 POST 请求
【解决方案2】:
import json

response_data = json.loads(response.text)
result = response_data.get('result')

您需要反序列化 response.text 以将其作为字典,然后使用相应的密钥用户 .getresult 是上述示例中的一个键。 response 是 url 调用的响应。

【讨论】:

  • object has no attribute 'text'"
  • 您的要求是这样的吗? response = requests.request("GET", url, data=payload, headers=headers, params=querystring)
  • 不,我使用 Flask 和 POST 方法
  • 我有端点,我需要从客户端获取 POST 数据:@app.route('/protocol/<token>', methods=['POST'])
  • 试试这个。 data = request.json request.json 是一个字典。
猜你喜欢
  • 2020-08-07
  • 1970-01-01
  • 2019-10-22
  • 2013-12-24
  • 2017-03-03
  • 1970-01-01
  • 1970-01-01
  • 2021-11-28
  • 2010-11-07
相关资源
最近更新 更多