PYTHON WITH FLASK Hello, I\'m working on a basic python flask program that works
ID: 3825170 • Letter: P
Question
PYTHON WITH FLASK
Hello, I'm working on a basic python flask program that works with json files and html. Basically, I need to read a json file that has am objects called 'races'. It needs to be able to read the file and then take the object and create a <SELECT> fields that will dynamically populate the drop down menu. So if I changed one of these things in the json file it will automatically change the name for the drop down.
Ex: Json file is
"races": {"half": "full"} so the drop down menu should have half and full as the possible choices. if i change half to mile it should have mile and full as the choices
I don't need full indepth code on setting up the server i just need the example for opening up the json file and then how it would look on the html webpage
Explanation / Answer
There is an error in json file.
It actually should be :
sample.json--------------------
{
"races": {"half": "full"}
}
demo.py----------
import json
from flask import Flask
app = Flask(__name__) # Construct an instance of Flask class for our webapp
@app.route('/') # URL '/' to be handled by main() route handler (or view function)
def main():
str = '<html>'
str += '<body><form>'
with open("sample.json") as json_file: # read data from file
json_data = json.load(json_file)
for key, value in json_data.items():
str = str + key + ' <select>'
for k, v in value.items():
str = str + '<option>' + k + '</option>'
str = str + '<option>' + v + '</option>'
str += '</select>'
str += '</form></body></html>'
return str
if __name__ == '__main__': # Script executed directly (instead of via import)?
app.run()
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.