title seems like a common problem but before marking as duplicate post please read at first
I am passing a javaScript object
via POST
method to Flask
. But I think it converts to JSON
format(due to insufficient knowledge I am not confident about this statement). On the client-side, I have printed the value of the JavaScript object and got
{
"0001_Summer": {
"value": [
"value_05",
"value_02",
"value_03"
]
},
"0003_Spring": {
"value": [
"All",
"value_04",
"value_03"
]
},
"0002_Winter": {
"value": [
"value_04",
"value_07",
"value_02"
]
},
"Query": "56"
}
The way of submission from JavaScript is as like as follows in my case
function POST_Query_data() {
hiddenform = document.createElement("form")
hiddenform.style.visibility = "hidden";
hiddenform.method = "POST";
// json_for_backend this is the final json in my case
for ([key, value] of Object.entries(json_for_backend)) {
i_1 = document.createElement("input");
i_1.name = key;
i_1.value = JSON.stringify(value);
hiddenform.appendChild(i_1);
}
document.getElementById("body").appendChild(hiddenform);
hiddenform.submit();
}
While I click on submit
then POST_Query_data
is triggered.
After passing this object via POST
method in Flask I have printed request.form
and got
ImmutableMultiDict([('0001_Summer', '{"value":["value_05","value_02","value_03"]}'), ('0003_Spring', '{"value":["All","value_04","value_03"]}'), ('0002_Winter', '{"value":["value_04","value_07","value_02"]}'), ('Query', '"56"')])
By following the documentation I have converted this ImmutableMultiDict
to a regular dict
type
from flask import Flask, render_template, request
@app.route('/', methods=['POST', 'GET'])
def foo(name=None):
if request.method == 'POST':
converted_dict = {}
converted_dict = request.form.to_dict()
return render_template('index.html',name=name)
After printing converted_dict
I have found
{'0001_Summer': '{"value":["value_05","value_02","value_03"]}', '0003_Spring': '{"value":["All","value_04","value_03"]}', '0002_Winter': '{"value":["value_04","value_07","value_02"]}', 'Query': '"56"'}
where it is seen that the value of each key(eg: 0001_Summer
) is a string while I need them also in a dict
type. I have found tons of post regarding conversion of string to dict
and followed one.
import ast
for a in converted_dict:
for key, val in ast.literal_eval(converted_dict[a]).items():
# done processing with "val"(dict type from string)
But I am looking for any faster way to convert from ImmutableMultiDict
to a nested dict
form as in the above process I have to iterate using a for loop
which I believe for a large data will cause a overhead.