将Flask表单数据转换为JSON只获取第一个值 [英] Converting Flask form data to JSON only gets first value
问题描述
我想从HTML表单输入并以JSON格式输出。当选择多个值时,它们不会被转换为JSON数组,只会使用第一个值。
@ app.route(' / form')
pre>
def show_form():
return render_template('form.html')
@ app.route(/ result,methods = ['POST' ])
def show_result():
result = request.form
return render_template('result.html',result = result)
form.html
:
< form method = POST>
<输入名称=服务器>
< option value =thor> thor< / option>
< option value =loki> loki< / option>
< option value =flash> flash< / option>
< option value =蝙蝠侠>蝙蝠侠< / option>
< / select>
< input type = submit>
< / form>
result.html
:
$ b{{result | tojson}}
当所有者的多个值被选中,thor和flash时,输出只显示一个值:
{server:app-srv,owners:thor}
我希望所有者成为一个列表:
{server:app-srv ,owners:[thor,flash]}
如何显示表单作为JSON而不会丢失列表值?
解决方案
request.form
是一个MultiDict
。遍历一个multidict只返回每个键的第一个值。要获取字典将会列出值,请使用 <$ c
$ b $result = request.form.to_dict(flat = $ c $ to_dict
) False)
为了保持一致性,所有的值都是列表,即使只有一个项目。如果要压扁单值项目,则需要手动处理数据。使用
iterlists
b
$ bresult = {
key:value [0] if len (value)== 1 else value
for key,request.form.itext()
}
I want to take input from an HTML form and give the output in JSON format. When multiple values are selected they are not converted into JSON arrays, only the first value is used.
@app.route('/form') def show_form(): return render_template('form.html') @app.route("/result", methods=['POST']) def show_result(): result = request.form return render_template('result.html', result=result)
form.html
:<form method=POST> <input name=server> <select name=owners multiple> <option value="thor">thor</option> <option value="loki">loki</option> <option value="flash">flash</option> <option value="batman">batman</option> </select> <input type=submit> </form>
result.html
:{{ result|tojson }}
When multiple values for owner are selected, "thor" and "flash", the output shows only one value:
{"server": "app-srv", "owners": "thor"}
I expect owners to be a list:
{"server": "app-srv", "owners": ["thor", "flash"]}
How do I display the form as JSON without losing list values?
解决方案
request.form
is aMultiDict
. Iterating over a multidict only returns the first value for each key. To get a dictionary will lists of values, useto_dict
.result = request.form.to_dict(flat=False)
All values will be lists, even if there's only one item, for consistency. If you want to flatten single-value items, you need to process the data manually. Use
iterlists
with a dict comprehension.result = { key: value[0] if len(value) == 1 else value for key, value in request.form.iterlists() }
这篇关于将Flask表单数据转换为JSON只获取第一个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!