我正在使用嵌套的mongo后端,并且正在将其映射到SQL数据库表。用户可以填写将按照以下方式存储的表格
{
"response": {
"question_1": "answer_1",
"question_2": [
"answer_a",
"answer_b"
]
},
"user": "user_1",
"form_id": "2344"
}
问题可以将多个答案存储为数组。 我想像这样将其扁平化为长格式(即每个问题/答案组合只有一条记录)
[
{
"question_id": "question_1",
"answer": "answer_1",
"user": "user_1",
"form_id": "2344"
},
{
"question_id": "question_2",
"answer": "answer_a",
"user": "user_1",
"form_id": "2344"
},
{
"question_id": "question_2",
"answer": "answer_b",
"user": "user_1",
"form_id": "2344"
}
]
在python中实现此目标的最有效方法是什么? 我可以通过遍历响应字典中的每个响应来强行使用它,但是我觉得那是太过分了...
非常感谢
编辑: 首次尝试使用以下功能:
def transform_responses_to_long(completed_form: Dict):
responses = completed_form["response"]
del completed_form["response"]
for key, values in responses.items():
if not isinstance(values, (List, Dict)):
values = [values]
for value in values:
result = {}
result.update(completed_form)
result.update({"question_id": key, "answer": value})
yield result
针对每个问题得出正确的格言:答案组合