RhysBuddy RhysBuddy - 5 months ago 18
JSON Question

print element from list json

i have a list a load from a txt file which is formatted with JSON, the program prints out the element i want (by index, requested from user) although it prints the list in an unwanted format

elif choice == 'v':
# View a joke.
# See Point 6 of the "Requirements of admin.py" section of the assignment brief.
jokeIndex = input('Joke number to view: ')
index = int(jokeIndex)
file = open('data.txt', 'r')
data = json.load(file)
print(data[index])

file.close();
pass


it prints it literally how it is written in the txt file, not just the actually elements


< Choose [a]dd, [l]ist, [s]earch, [v]iew, [d]elete or [q]uit.

< v

< Joke number to view: 1

< {'setup': 'whats brown and sticky', 'punchline': 'a stick'}


although i would like it to output something like this


< Q:whats brown and sticky? A: a stick

Answer

You need to format the output more

elif choice == 'v':

jokeIndex = input('Joke number to view: ')
index = int(jokeIndex)
file = open('data.txt', 'r')
data = json.load(file)
print('Q: ' + data[index]['setup'])
print('A: ' + data[index]['punchline'])

file.close();
pass
Comments