flask中jsonify和json.dumps的區別

1. json.dumps()用於將dict類型的數據轉成str

@app.route('/json')
def demo1():
    my_dict = {'name':'dongge','age':30}
    return json.dumps(my_dict)
    # return jsonify(my_dict)
{"age": 30, "name": "dongge"}
HTTP/1.0 200 OK

Content-Type: text/html; charset=utf-8

Content-Length: 29

Set-Cookie: session=eyJuYW1lIjp7IiBiIjoiY0hsMGFHOXVNalE9In19.DYYwPw.NcRdbLbteD6X7q56CCfJBbCnKrc; HttpOnly; Path=/

Server: Werkzeug/0.12.2 Python/2.7.12

Date: Sun, 11 Mar 2018 03:13:03 GMT

2.jsonify返回一個json對象

@app.route('/json')
def demo1():
    my_dict = {'name':'dongge','age':30}
    # return json.dumps(my_dict)
    return jsonify(my_dict)
{
  "age": 30, 
  "name": "dongge"
}
HTTP/1.0 200 OK

Content-Type: application/json

Content-Length: 36

Set-Cookie: session=eyJuYW1lIjp7IiBiIjoiY0hsMGFHOXVNalE9In19.DYYwuA.RTNYDDNa3a4zknHaZdaV_Kib_EM; HttpOnly; Path=/

Server: Werkzeug/0.12.2 Python/2.7.12

Date: Sun, 11 Mar 2018 03:15:04 GMT

jsonify源碼

def jsonify(*args, **kwargs):
indent = None
    if current_app.config['JSONIFY_PRETTYPRINT_REGULAR'] \
        and not request.is_xhr:
        indent = 2
    return current_app.response_class(dumps(dict(*args, **kwargs),
        indent=indent),
        mimetype='application/json')

個人理解:

1,json.dumps只是將dict類型轉化爲str類型,並非一個json對象,我理解的是擁有json格式的字符串。

2,jsonify其實也是用dumps方法轉換成了json格式的字符串,只不過在最後改變了傳輸的數據類型。

3,jsonify將dict類型轉變爲json對象。



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章