Python中针对JSON对象的发布请求

时间:2018-11-15 23:13:55

标签: python json pandas api

我在熊猫中有一个数据框(df),我已将其转换为JSON formot:

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(说))(有效)作为发送数据时

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

我想念什么,这是什么问题?

2 个答案:

答案 0 :(得分:0)

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

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

,但是json的{​​{1}}关键字参数需要一个python对象。如果要提交子字符串,请改用requests.post参数:

data=

我不确定是否需要编码。

答案 1 :(得分:0)

您可以利用 New-AzureRmResourceGroupDeployment -ResourceGroupName $resourceGroupName ` -Name $deploymentName ` -Mode Incremental ` -TemplateUri ($templateUri + $templateToken) ` -location $location ` -applicationGatewayName $applicationGatewayName ` -applicationGatewaySize $applicationGatewaySize ` -wafMode $wafMode ` -wafRuleSetVersion $wafRuleSetVersion ` -appGwPublicIpName $appGwPublicIpName ` -createNewVirtualNetwork $createNewVirtualNetwork ` -virtualNetworkName $virtualNetworkName ` -virtualNetworkAddressPrefix $virtualNetworkAddressPrefix ` -appGWSubnetName $appGWSubnetName ` -appGatewaySubnetPrefix $appGatewaySubnetPrefix ` -appGWNsgName $appGWNsgName ` -applicationGatewayInstanceCount $applicationGatewayInstanceCount ` -httpListenerName $httpListenerName ` -httpListenerHostName $httpListenerHostName ` -httpListenerServerNameIndication $httpListenerServerNameIndication ` -frontEndPort $frontEndPort ` -frontEndProtocol $frontEndProtocol ` -backendAddressPoolName $backendAddressPoolName ` -backendIPAddresses $backendIPAddresses ` -backEndPort $backEndPort ` -backEndProtocol $backEndProtocol ` -cookieBasedAffinity $cookieBasedAffinity ` -SSLCertificateName $SSLCertificateName ` -frontendCertData $frontendCertData ` -frontendCertPassword $frontendCertSecuredPassword ` -routingRulesName $routingRulesName ` -routingRulesType $routingRulesType ` | Out-Null simplejson软件包:

json

此外,如果您不想将其定位为记录,则可以使用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'} ) 包中的data参数接受一个字符串。