Converting Flask form data to JSON only gets first value

后端 未结 1 850
挽巷
挽巷 2020-11-30 11:01

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

相关标签:
1条回答
  • 2020-11-30 11:30

    request.form is a MultiDict. Iterating over a multidict only returns the first value for each key. To get a dictionary with lists of values, use to_dict(flat=False).

    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()
    }
    
    0 讨论(0)
提交回复
热议问题