3

I have made a simple HTML form on a page and I would like to gather all the data from the form, convert it to JSON, then display that JSON on a new page. I don't need or want a database to save this data, I just want it to spit out onto a new page in proper JSON format so that the person using it can copy/paste that data for something else.

I'm using Flask, here is the HTML form I made that extends another basic layout page:

{% extends "layout.html" %}
    {% block content %}
        <div class="container">
        <form action="/display" method="post" id="employForm"
        <fieldset>
        <label>First Name
          <input type="text" name="firstName" placeholder="Joe" required>
        </label>
        <label>Last Name
          <input type="text" name="lastName" id="lastName" placeholder="Schmoe" required>
        </label>

        <label>
        Department
          <select name="department" required>
            <option value="sales">Sales</option>
            <option value="marketing">Marketing</option>
            <option value="developer">Developer</option>
            <option value="business">Business Relations</option>
            <option value="sysAdmin">Systems Administration</option>
            <option value="drone">Drone</option>
          </select>
        </label>
            ... goes on
        </fieldset>
      <button class="button-primary" type="submit" value="Submit" form="employForm">SUBMIT!</button>
    </form>
  </div>
    {% endblock %}

The form is a bit longer than that and contains several different types of form data. Here is the server side of things (the flask app I made):

from flask import Flask, render_template, request, jsonify

app = Flask(__name__)

@app.route('/')
def hello():
     return render_template('home.html')

@app.route('/display', methods=["GET", "POST"])
def display():
     result = request.form
     return render_template('display.html', result=result)


if __name__ == "__main__":
     app.run(host='0.0.0.0')

I feel like I'm close. At the moment, after I hit submit I get redirected to the display page and it prints out something like the following (specific data changes based on input answers, obviously):

ImmutableMultiDict([('startDate', u'2016-08-03'), ('employmentStatus', u'intern'), ('firstName', u'Hola'), ('lastName', u'Schmoe'), ('department', u'marketing'), ('location', u'SanFran'), ('inNYC', u'Yes'), ('requests', u'Blah blah try this.')])

I've done quite a bit of searching on Stack Overflow and elsewhere... the problem I've encountered is that they all provide examples where a person only wants to collect one or two keys off of their form, not the whole form.

Additionally, for my particular purposes I would strongly prefer that the data be returned as JSON and displayed as such on the display.html page.

For reference, here are some of the questions I looked at that didn't quite help:

How to post data structure like json to flask?

Getting form data from html form using flask and python

Flask request and application/json content type

Send Data from a textbox into Flask?

Any guidance is much appreciated. Thank you!

Community
  • 1
  • 1
RHdev
  • 33
  • 1
  • 1
  • 4
  • If that's all you're doing, you don't need Flask. You can do it all with HTML and JavaScript. – dirn Aug 19 '16 at 22:47
  • Can you explain what you mean? Are you talking about using GET instead of POST and assigning a click event with JavaScript? If so, I thought about that option but ultimately decided that I wanted to practice using python/ Flask. Also this might turn into a more complicated project later on, so I decided using Flask was the better idea. – RHdev Aug 20 '16 at 18:35
  • No. If all you're doing is displaying the form fields as JSON on the page, you don't need to make any HTTP requests. You can use JavaScript to capture form submission and covert the fields to JSON (using something like [jQuery's `serializeArray`](http://api.jquery.com/serializeArray/)). – dirn Aug 20 '16 at 18:52
  • I see, that makes a lot of sense. The reason I'm using Flask however is not for this particular task but for the longer-term project which will need to be more complex, ultimately. Thank you for your help. – RHdev Aug 20 '16 at 23:26

2 Answers2

5

I see you import jsonify... you could use that...

@app.route('/display', methods=["GET", "POST"])
def display():
     return jsonify(request.form)

or you could use the tojson filter in your template

{{ result | tojson }}

or

result = json.dumps(request.form)

I think any of those will work.

GMarsh
  • 2,401
  • 3
  • 13
  • 22
  • I've tried the second option and it worked, thank you! I will try the other options in a bit and give my feedback. – RHdev Aug 20 '16 at 19:07
0
@app.route('/form2json',methods=['POST','GET'])
def form2json():
import json
if request.method == 'POST':
    f=json.dumps(request.form)
    return jsonify(f)
elif request.method =='GET':
    from forms import Some_Form
    return Some_Form()

I had to first dump it into json then turn it jsonify it

Max
  • 4,152
  • 4
  • 36
  • 52