简体   繁体   中英

Iterate over ImmutableMultiDict and transform it into a unique json object

I am working on a web app that works as a poll creation at the moment i am sending the questions from the frontend to the backend (made in flask) this is an example of the data i am sending:

ImmutableMultiDict(
    [
        ('select', 'Do you like dogs?'),
        ('option1', 'Yes'),
        ('option2', 'No'),
        ('text', 'Why do you like dogs?'),
        ('textField', ''),
        ('range', 'How much do you like dogs?'),
        ('rangeField', '2.5')
    ]
)

As you can see the option1 and option 2 are the available answers of the first question (which is a select form with the question 'Do you like dogs?'), i would like to iterate over the elements of this question and output an object like this:

[
   {
      "title":"Do you like dogs?",
      "type":"select",
      "options":[
         "Yes",
         "No"
      ]
   },
   {
      "title":"Why do you like dogs?",
      "type":"text"
   },
   {
      "title":"How much do you like dogs?",
      "type":"range"
   }
]

At the moment this is the code i am using:

questions = []
currQuestion = None
while x in request.form:
    if(x == 'select' or x == 'checkbox' or x == 'choices' or x == 'text' or x == 'range' or x == 'date'):
        if currQuestion != None:
            questions.append(currQuestion)
            currQuestion = { "title": x, "type": x }
    elif not (x == 'textField' or x == 'rangeField' or x == 'dateField'):
        if(not currQuestion.options):
            currQuestion.options = []
        currQuestion.options.append(x)

Note that textField and rangeField values are ignored. I am new to python so i don't understand it deeply that's why this question is pretty easy.

You can iterate over the key-value pairs of the ImmutableMultiDict and build the result by checking the key name:

from werkzeug.datastructures import ImmutableMultiDict #for testing purposes
data = ImmutableMultiDict([('select', 'Do you like dogs?'), ('option1', 'Yes'), ('option2', 'No'), ('text', 'Why do you like dogs?'), ('textField', ''), ('range', 'How much do you like dogs?'), ('rangeField', '2.5')])
r, l, valid = [], None, {'select', 'text', 'range'}
for a, b in data.items():
   if a in valid:
      l = a
      r.append({'title':b, 'type':a})
   elif a.startswith('option') and l == 'select':
      r[-1]['options'] = [*r[-1].get('options', []), b]

print(r)

Output:

[{'title': 'Do you like dogs?', 'type': 'select', 'options': ['Yes', 'No']}, 
 {'title': 'Why do you like dogs?', 'type': 'text'}, 
 {'title': 'How much do you like dogs?', 'type': 'range'}]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM