【问题标题】:Post Requests in Python For JSON Objects在 Python 中为 JSON 对象发布请求
【发布时间】:2019-04-19 03:07:52
【问题描述】:

我在 pandas 中有一个数据框 (df),我已将其转换为 JSON 格式:

json_obj = df.to_json(orient=records).

json 对象看起来像(比如说):

json_obj = [
    {"a": "xxx", "b":"pqr", "c": 1},
    {"a": "uuy", "b":"abc", "c": 3},
    {"a": "yty", "b":"nnq", "c": 7}
]

现在当我使用 API URL (urlex (say)) (valid) as 发送数据时

import requests

r1 = requests.post('urlex', json = [
    {"a": "xxx", "b":"pqr", "c": 1},
    {"a":"uuy", "b":"abc", "c": 3},
    {"a": "yty", "b":"nnq", "c": 7}
]

print (r1.status_code)

print(r1.content)

我得到**b'{"success":true}'**的响应代码200

但是,当我对

做同样的事情时
r1 = requests.post('urlex', json = json_obj ]

print (r1.status_code)

print(r1.content)

我得到**b'{"success":false}'**的响应代码200

我错过了什么,有什么问题?

【问题讨论】:

    标签: python json pandas api


    【解决方案1】:

    我认为你的问题是 pd.DataFrame.to_json 返回一个字符串:

    data = pd.DataFrame({'a': [1, 2]})
    type(data.to_json())
    str
    

    但是requests.postjson 关键字参数需要一个python 对象。如果要提交子字符串,请改用data= 参数:

    # this submits a jsonified string
    response = requests.post('http://localhost:8888', json=data.to_json())
    print(response.request.body.decode('utf-8'))
    "{\"a\":{\"0\":1,\"1\":2}}"
    
    
    # this submits the actual json object
    response = requests.post(
        'http://localhost:8888',
        data=data.to_json().encode('utf-8'),
        headers={'Content-Type': 'application/json'}
    )
    print(response.request.body.decode('utf-8')
    {"a":{"0":1,"1":2}}
    

    我不确定是否需要编码。

    【讨论】:

      【解决方案2】:

      您可以利用 simplejsonjson 软件包:

      import simplejson as json
      
      response = requests.post('http://localhost:8888', data=json.loads(df.to_json(orient='records')),
      headers={'Content-Type': 'application/json'}
      )
      

      此外,如果您不想定位为记录,可以使用 to_dict 而不是 to_json

      response = requests.post('http://localhost:8888', data=df.to_dict(),
      headers={'Content-Type': 'application/json'}
      )
      

      之所以有效是因为requests 包中的data 参数接受一个字符串。

      【讨论】:

      • @Stan 是的,这也是解决问题的替代方法
      • 谢谢!!我也会试试你的。有很多方法总是更好
      猜你喜欢
      • 2018-10-24
      • 2014-12-08
      • 2020-12-11
      • 1970-01-01
      • 2020-02-11
      • 2013-10-26
      • 2018-06-15
      • 1970-01-01
      • 2021-02-26
      相关资源
      最近更新 更多