向需要包含JSON数组的Node.js服务器POST Python列表
我正在尝试用Python向一个服务器发送一个POST请求,这个服务器希望接收到一个包含JSON的数组。但是我似乎无法正确格式化数据。请问我该如何把下面的内容格式化成像JavaScript数组那样,以便Node.js服务器能够识别?
POST /api/adduser/
Node.js期望的内容格式:
[
{'user':'jon','email':'email@gmail.com'},
{'user':'jon2','email':'email2@gmail.com'}
]
我现在的代码:
import requests
import json
payload = \
[
{
'user': 'hello',
'email': 'hello@gmail.com'
},
{
'user': 'helloAgain',
'email': 'helloAgain@gmail.com'
}
]
res = requests.post('http://localhost/api/users', data=json.dumps(payload))
#res -> 400 error -> reason: "wrong json format - must be an array"
2 个回答
0
这里是解决方案:
发送请求 到 /api/adduser/
Node.js 期望的数据格式:
[
{'user':'jon','email':'email@gmail.com'},
{'user':'jon2','email':'email2@gmail.com'}
]
我现在的代码:
import requests
import json
payload = \
[
{
'user': 'hello',
'email': 'hello@gmail.com'
},
{
'user': 'helloAgain',
'email': 'helloAgain@gmail.com'
}
]
jsonPayload = json.dumps(payload)
headers = {'Content-Type': 'application/json'}
res = requests.post('http://localhost/api/users', data=jsonPayload, headers=headers)
1
你期望的数据格式不对(它不是JSON格式)。为了避免很多麻烦,建议你使用 json
模块:
import json
res = requests.post('http://localhost/api/users', data=json.dumps(payload))