如何将多维数组编码为JSON?

2024-05-19 20:27:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试将多维数组作为JSON发送到Python后端。 数组存储在画布上绘制的点,并将用于执行一些计算。我需要如何对数据进行编码?你知道吗

我试过使用这个函数JSON.stringify文件但我仍然没有从后端获取数据。你知道吗

后端功能,在本地主机端口5000上运行:

@app.route('/canvas-roi', methods=['POST'])
def canvasRoi():
    print(request.body)

存储数据的数组并插入示例:

private points = [];
points.push([1, 2]);
points.push([3, 4]);

前端函数将数组作为JSON发送到后端:

onUpload(){
      var output = {};
      for(var i = 0; i<this.points.length; i++) output[i] = this.points[i];
      this.http.post("http://localhost:5000/canvas-roi", JSON.stringify(output)).subscribe(res => {console.log(res);});

    }

我希望后端接收JSON并在控制台中打印。但是,在后端,实际输出是

AttributeError: 'Request' object has no attribute 'body'

以及

127.0.0.1 - - [05/Jun/2019 17:10:59] "POST /canvas-roi HTTP/1.1" 500 -

在前端,错误消息是:

POST http://localhost:5000/canvas-roi 500 (INTERNAL SERVER ERROR)

我知道错误一定是关于我如何创建post请求,但我不知道如何解决这个问题。你知道吗


Tags: 数据函数jsonhttpoutputvarbody数组
2条回答

您正在加载表单数据,但正在发送JSON。这和你的问题有关吗?How to receive json data using HTTP POST request in Django 1.6?

问题既在于我创建post请求的方式,也在于我如何尝试提取它。以下代码解决了问题:

后端功能:

@app.route('/canvas-roi', methods=['POST'])
def canvasRoi():
    data = request.json

前端功能:

onUpload(){
    let requestOptions = {headers: new HttpHeaders({'Content-Type':  'application/json'})};
    this.http.post("http://localhost:5000/canvas-roi", this.points, requestOptions);
}

相关问题 更多 >