flask处理json的多种情况|flask传递json数组

flask处理json的多种情况|flask传递json数组

flask处理json的多种情况


研究了一晚上flask处理json的几种方式,首先要明确ajax传输的数据格式,其次是flask在后台处理的方式。

json传输方式

键值对方式

var json = {"hubei":"hubei"};$.post('post/', json, function(data) {    /*optional stuff to do after success */    console.log(data);});

直接定义一个json数据,post方法会自动处理成键值对的形式

JSON.stringify()强制转换

看到别人的解决办法,改成这样的形式即

var json = {"hubei":"hubei"};$.post('post/', JSON.stringify(json), function(data) {    /*optional stuff to do after success */    console.log(data);});

这样的数据在传输时实际是整个json以字符串的形式在键位,而值是空的。

flask处理数据方式

在flask的文档可以看到,处理request的请求数据这部分有好几种。

form

A MultiDict with the parsed form data from POST or PUT requests. Please keep in mind that file uploads will not end up here, but instead in the files attribute.

args

A MultiDict with the parsed contents of the query string. (The part in the URL after the question mark).

values

A CombinedMultiDict with the contents of both form and args.

data

Contains the incoming request data as string in case it came with a mimetype Flask does not handle.

get_json(force=False, silent=False, cache=True)

Parses the incoming JSON request data and returns it. If parsing fails the on_json_loading_failed() method on the request object will be invoked. By default this function will only load the json data if the mimetype is application/json but this can be overriden by the force parameter.
Parameters:
force – if set to True the mimetype is ignored.
silent – if set to False this method will fail silently and return False.
cache – if set to True the parsed JSON data is remembered on the request.

json

If the mimetype is application/json this will contain the parsed JSON data. Otherwise this will be None.
The get_json() method should be used instead.

根据json两种post方式,分别把每种数据都输出看一下

@app.route('/post/', methods=['POST'])def post_test():    print request.form, request.args, request.values, request.data, request.get_json(), request.get_json(force=True), request.json    json_data = request.form    return jsonify(json_data)

键值对方式

输出的结果是:
request.form:ImmutableMultiDict([(‘hubei’, u’hubei’)])
request.args:ImmutableMultiDict([])
request.values:CombinedMultiDict([ImmutableMultiDict([]), ImmutableMultiDict([(‘hubei’, u’hubei’)])])
request.data:空白字符串
request.get_json()request.json:None
request.get_json(force=True):加上force=True是强制转换,此时会报400错误

JSON.stringify()强制转换

输出的结果是:
request.form:ImmutableMultiDict([(‘{“hubei”:”hubei”}’, u”)])
request.args:ImmutableMultiDict([])
request.values:CombinedMultiDict([ImmutableMultiDict([]), ImmutableMultiDict([(‘{“hubei”:”hubei”}’, u”)])
request.data:空白字符串
request.get_json()request.json:None
request.get_json(force=True):加上force=True是强制转换,此时会报400错误

可以看出最好的办法是从request.form里面获取数据。
但是把ImmutableMultiDict强制转换成dict之后,格式是{“hubei”:[“hubei”]},最后用python做了一下处理:

json_data = {key:dict(request.form)[key][0] for key in dict(request.form)}

完工

推荐阅读