python flask解析json数据不完整的解决方法

yipeiwu_com5年前Python基础

当使用Python的flask框架来开发网站后台,解析前端Post来的数据,通常都会使用request.form来获取前端传过来的数据,但是如果传过来的数据比较复杂,其中右array,而且array的元素不是单个的数字或者字符串的时候,就会出现解析不到数据的情况,比如使用下面的js代码向python flask传递数据

$.ajax({
  "url":"/test",
  "method":"post",
  "data":{
      "test":[
        {"test_dict":"1"},
        {"test_dict":"2"},
        {"test_dict":"3"},
        ]
      }
  }
)

当我们使用flask的request.form获取前端的数据时,发现获取到的数据是这样的:

ImmutableMultiDict([('test', 'test_dict'), ('test', 'test_dict'), ('test', 'test_dict')])

???我的Post数据呢?给我post到哪里去了???

这里我就去网上查解决办法,但是网上哪些删么使用reqeust.form.getlist()方法好像都对我无效,但是又找不到其他的解决方案?怎么办?

规范一下自己的请求,在前端请求的时候设置一个Json的请求头,在flask框架钟直接使用json.loads()方法解析reqeust.get_data(as_text=True),就可以解析到完整的post参数了!

前端:

$.ajax({
  "url":"/test",
  "method":"post",
  "headers":{"Content-Type": "application/json;charset=utf-8"},//这一句很重要!!!
  "data":{
    "test":[
        {"test_dict":"1"},
        {"test_dict":"2"},
        {"test_dict":"3"},
      ]
    }
  }
  )

python代码:

@app.route("/test",methods=["GET","POST"])
def test():
  print(json.loads(request.get_data(as_text=True)))
  return ""

然后看看后台打印的信息:

* Serving Flask app "test_flask.py"
* Environment: development
* Debug mode: off
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
{'test': [{'test_dict': '1'}, {'test_dict': '2'}, {'test_dict': '3'}]}
127.0.0.1 - - [25/May/2019 22:43:08] "POST /test HTTP/1.1" 200 -

问题解决,可以解析到完整的json数据啦!

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

python 通过 socket 发送文件的实例代码

python 通过 socket 发送文件的实例代码

目录结构: client: #!/usr/bin/env python # -*-coding:utf-8 -*- import socket, struct, json down...

Python2.7 实现引入自己写的类方法

系统环境:win10 开发环境:JetBrains PyCharm 2017.1.5 x64 Python版本:2.7 假如我们有一个class叫DBUtil,它在A.py里(最好一...

Python字符串转换成浮点数函数分享

利用map和reduce编写一个str2float函数,把字符串'123.456'转换成浮点数123.456 from functools import reduce def s...

python中关于日期时间处理的问答集锦

如何在安装setuptools模块时不生成egg压缩包而是源码     Q:如何在安装setuptools模块时不生成egg压缩包而是源码,这样有时可以修改...

Python基础教程之浅拷贝和深拷贝实例详解

Python基础教程之浅拷贝和深拷贝实例详解            网上关于Pytho...