2

Here I have a dict,

dict1 = {'name':"max","age":20}

What I want to do is to save the dict into a json file.

@bp_main.route('/download/json', methods=['GET'])
def get_sample_json_file():
    dict1 =  {'name':"max","age":20}
    return ???

What I did now, is to save dict1 into a real json file, and use flask send_from_directory to return the file. How to avoid saving dict1 into disk?

McCree Feng
  • 179
  • 4
  • 12

1 Answers1

2

This will just return the dictionary what you have and by that you don't have to save dictionary to file.

from flask import Response
import json


@bp_main.route('/download/json', methods=['GET'])
def get_sample_json_file():
    dict1 =  {'name':"max","age":20}
    return Response(json.dumps(dict1), status=200, mimetype='application/json')

You can also try jsonify response. But I prefer Response way.

Shakeel
  • 1,869
  • 15
  • 23