我正在尝试编写一个程序,允许用户输入问题和答案以进行多项选择测验。需要将问题和答案写入json格式的文件中。
到目前为止,我的代码会询问用户一个问题,问题的正确答案,然后是3个不正确的答案,并将所有字符串写入文件。但我不知道如何将字符串转换为json,因此可以在测验中使用它们。
我到目前为止的守则是:
def addToList(filename, data):
question = input('Add Question: ') # prompt user to type what to add
correct = input('Add Correct Answer: ')
wrong1 = input('Add 1st Incorrect Answer: ')
wrong2 = input('Add 2nd Incorrect Answer: ')
wrong3 = input('Add 3rd Incorrect Answer: ')
question = question + '\n' # add a line break to the end
correct = 'correct: ' + correct
wrong1 = 'wrong1: ' + wrong1
wrong2 = 'wrong2: ' + wrong2
wrong3 = 'wrong3: ' + wrong3
data.append(question) # append the question
data.append(correct)
data.append(wrong1)
data.append(wrong2)
data.append(wrong3)
f = open(filename, 'a') # open the file in append mode
f.write(question) # add the new item to the end of the file
f.write(correct)
f.write(wrong1)
f.write(wrong2)
f.write(wrong3)
f.close()
抱歉,我知道这是一个新手问题,但我完全迷失在这里,找不到任何用户输入放入Json的例子。
答案 0 :(得分:4)
首先构建dictionary
,然后将其转换为JSON
。
像这样:
import json
# (...)
correct = 'correct: ' + correct
wrong1 = 'wrong1: ' + wrong1
wrong2 = 'wrong2: ' + wrong2
wrong3 = 'wrong3: ' + wrong3
dic = {'correct': correct, 'wrong1': wrong1, 'wrong2': wrong2, 'wrong3': wrong3}
json_str = json.dumps(dic)