2

I can get json from HTML form but the problem is that all of value in side json are convert to string type. I have try both
result = json.dumps(request.form) result = jsonify(request.form) but result still be the same. HTML form Output Json

Is there any way to get the result like this { "department": "sales", "donation": 1538, "firstName": "abc", "lastName": "ccc" }

HTML Code

<!doctype html>
<html>
   <body>
<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>Homeless cat donation
          <input type="number" name="donation" id="donation" placeholder=1234 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="operation">Operation</option>
          </select>
        </label>
            Thanks
        </fieldset>
      <button class="button-primary" type="submit" value="Submit" form="employForm">SUBMIT!</button>
    </form>
    </body>
  </div>
 </html>

This is the python flask code

from flask import Flask, render_template, request, jsonify
import json

app = Flask(__name__)
@app.route('/')
def hello():
     return render_template('layout.html')

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

if __name__ == "__main__":
      app.run(debug = True)
  • I suggest that you try doing json.loads to first convert it back to a dictionary and then json.dumps. How does it turn out? – Edison Jun 02 '20 at 07:32
  • 1
    Thanks, but the result is { "department": "sales", "donation": "1538", "firstName": "abc", "lastName": "ccc" } Value of donation does not keep format as number – Nut Trathitephun Jun 02 '20 at 10:00

1 Answers1

0

Taking notes from this Answer Here

JSON is untyped. Anything sent in JSON format will be converted to a string; so its not possible to send the donation value as an integer.

Edison
  • 870
  • 1
  • 13
  • 28