7: Saving Form Data to a JSON File in Flask

Introduction

In Flask web development, saving user-submitted data efficiently is essential for building robust applications. While databases are commonly used for data storage, for simple data structures like key-value pairs, a JSON file can be a suitable alternative. In this blog post, we’ll explore how to save form data to a JSON file in a Flask application.

Understanding the Approach

When a user submits a form with data like a URL and its corresponding nickname, we want to save this information for future reference. To achieve this, we’ll follow these steps:

  1. Create a dictionary to store the form data.
  2. Serialize the dictionary to JSON format.
  3. Write the JSON data to a file.

Implementing the Solution

Let’s dive into the code and see how we can implement this solution in our Flask application.

				
					from flask import Flask, render_template, request
import json

app = Flask(__name__)

@app.route('/shorten', methods=['POST'])
def shorten_url():
    # Create a dictionary to store form data
    URLs = {}
    code = request.form['code']
    URL = request.form['URL']
    
    # Check if the code already exists in the JSON file
    with open('urls.json', 'r') as url_file:
        URLs = json.load(url_file)
        if code in URLs:
            return "Code already exists. Please choose a different one."
    
    # Add new entry to the dictionary
    URLs[code] = {'URL': URL}
    
    # Write the dictionary to the JSON file
    with open('urls.json', 'w') as url_file:
        json.dump(URLs, url_file)
    
    return "URL successfully shortened!"

if __name__ == "__main__":
    app.run(debug=True)

				
			

Explanation

  • We define a route /shorten to handle POST requests containing form data.
  • Within the route, we create a dictionary URLs to store the form data.
  • We retrieve the form data (code and URL) submitted by the user.
  • We check if the code already exists in the JSON file to avoid duplicates.
  • If the code doesn’t exist, we add a new entry to the dictionary.
  • We serialize the dictionary to JSON format and write it to the urls.json file.

Conclusion

In this blog post, we’ve demonstrated how to save form data to a JSON file in a Flask application. By following these steps, you can efficiently store and manage user-submitted data without the need for a database. This approach is particularly suitable for simple data structures and can be easily extended to accommodate more complex requirements.

By incorporating this technique into your Flask projects, you can enhance data management and streamline your application’s functionality.