0

I'm trying to write a program that allows a user to input Questions and Answer for a multi-choice quiz. The questions and answers need to be written to a file in json format.

So far I have code that will ask the user for a Question, the correct answer to the question, then 3 incorrect answers, and write all the strings to a file. But I don't know how to convert the strings to json so they can be used in the Quiz.

The Code I have so far is:

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()

Sorry, I know this is a newbie problem but I'm totally lost here and can't find any examples of user input being put into Json.

1

1 Answer 1

4

First you build a dictionary, then convert it to JSON.

Like this:

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.