将 Flask 表单数据转换为 JSON 仅获取第一个值 [英] Converting Flask form data to JSON only gets first value

查看:20
本文介绍了将 Flask 表单数据转换为 JSON 仅获取第一个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从 HTML 表单中获取输入并以 JSON 格式提供输出.选择多个值时,它们不会转换为 JSON 数组,只会使用第一个值.

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 }}

当为owner选择多个值时,thor"和flash",输出只显示一个值:

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"]}

如何在不丢失列表值的情况下将表单显示为 JSON?

How do I display the form as JSON without losing list values?

推荐答案

request.form 是一个 MultiDict.迭代 multidict 只返回每个键的第一个值.要获取包含值列表的字典,请使用 to_dict(flat=False).

result = request.form.to_dict(flat=False)

为了一致性,所有值都将是列表,即使只有一项.如果要展平单值项目,则需要手动处理数据.使用 iterlists 与字典理解.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆