Skip to main content
 首页 » 编程设计

python之将 Python 列表发布到 Node.js 服务器,期望有效负载由包含 JSON 的数组组成

2025年05月04日13shangdawei

我正在尝试向需要包含 JSON 的数组的服务器发送 POST 请求(在 Python 中)。我似乎无法正确格式化数据。如何格式化以下有效负载,使其表现得像 Node.js 服务器的 JavaScript 数组?

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" 

请您参考如下方法:

您预期的负载不正确(它不是 JSON)。使用 json 模块可以省去很多麻烦:

import json 
res = requests.post('http://localhost/api/users', data=json.dumps(payload))