Skip to content Skip to sidebar Skip to footer

Convert Received Json To Dictionary, And Save To Local Disk

My flask server receives a json file. @app.route('/process', methods=['POST']) def trigger_processing(): sent_files = request.files json_file = sent_files['file'] print(js

Solution 1:

It fails because sent_files['file'] is a FileStorage object type, you need to read it and decode the bytes readed into a string. Then you can load it as a json.

from flask import Flask, request
from flask import make_response
from tempfile import gettempdir
import json
import os

app = Flask(__name__)

@app.route('/process', methods=['POST'])
def trigger_processing():
    sent_files = request.files
    #read the file
    json_file_content = sent_files['file'].read().decode('utf-8')
    #load the string readed into json object
    json_content = json.loads(json_file_content)
    print(json_content)
    #generate the path where you want to save your file (in my case the temp folder)
    save_path = os.path.join(gettempdir(), sent_files['file'].filename)
    #and save the file
    with open(save_path, 'w') as outfile:
        json.dump(json_content, outfile, indent=2)
    return make_response(json.dumps({'fileid': "ok"}), 200)

Post a Comment for "Convert Received Json To Dictionary, And Save To Local Disk"