替换 json 中的项目

问题描述 投票:0回答:1
{
    "question": "Alfred Nobel who invented dynamite was a student of which famous inventor?",
    "choice1": "James Harrison",
    "choice2": "Henri Giffard",
    "choice3": "Alexander Parkes",
    "choice4": "Ascanio Sobrero",
    "answer": "4"
},
{
    "question": "In which year did 'James Watson' and 'Francis Crick' discover one of the most famous inventions which changed the world.",
    "choice1": "1819",
    "choice2": "1946",
    "choice3": "1953",
    "choice4": "1962",
    "answer": "3"
},

我创建了一个包含 10,000 个问题和多个答案的数据库。导出为json格式。我想在另一个测验中使用这些数据,但使用一个正确答案。因此,我想用正确的文本更改 :answer: '1',然后删除“选项及其数据,留下问题和正确的答案。任何帮助将不胜感激。

json substitution
1个回答
0
投票

您可以使用

python
轻松完成。我提供示例代码:

import json

data = [
    {
        "question": "Alfred Nobel who invented dynamite was a student of which famous inventor?",
        "choice1": "James Harrison",
        "choice2": "Henri Giffard",
        "choice3": "Alexander Parkes",
        "choice4": "Ascanio Sobrero",
        "answer": "4"
    },
    {
        "question": "In which year did 'James Watson' and 'Francis Crick' discover one of the most famous inventions which changed the world.",
        "choice1": "1819",
        "choice2": "1946",
        "choice3": "1953",
        "choice4": "1962",
        "answer": "3"
    }
]

new_data = []

for item in data:
    correct_answer_key = f"choice{item['answer']}"
    correct_answer_text = item[correct_answer_key]
    
    new_data.append({
        "question": item["question"],
        "answer": correct_answer_text
    })

with open('new_quiz.json', 'w') as outfile:
    json.dump(new_data, outfile, indent=4)

print(json.dumps(new_data, indent=4))

结果:

[
    {
        "question": "Alfred Nobel who invented dynamite was a student of which famous inventor?",
        "answer": "Ascanio Sobrero"
    },
    {
        "question": "In which year did 'James Watson' and 'Francis Crick' discover one of the most famous inventions which changed the world.",
        "answer": "1953"
    }
]
© www.soinside.com 2019 - 2024. All rights reserved.