0

I used below code to store student information but I get only one value appearing in the json file.

import json

def get_studentdetails():
    data={}
    data['name']=input("Enter Student name")
    data['class']=input("Enter Class")
    data['maths']=input("Enter Marks for Maths")
    data['eng']=input("Enter English Marks")
    data['sci']=input("Enter Science Marks")
    return (data)

out={}
while True:
    quit=input("Enter Y/N to continue")
    if quit.lower()=='n':
        break
    else:
       out['Student_Detail']= get_studentdetails()

    with open('students.json','w') as file:
        json.dump(out,file,indent=2)

2 Answers 2

1

It is because you are overwriting your file after each while loop. Do the writing to file outside. Also, You want to store student into list.

import json

def get_studentdetails():
    data={}
    data['name']=input("Enter Student name")
    data['class']=input("Enter Class")
    data['maths']=input("Enter Marks for Maths")
    data['eng']=input("Enter English Marks")
    data['sci']=input("Enter Science Marks")
    return (data)
out=[]
while True:
    quit=input("Enter Y/N to continue")
    if quit.lower() == 'n':
        break
    record = get_studentdetails()
    out.append(record)


with open('students.json','w') as file:
    json.dump(out,file,indent=2)

Sign up to request clarification or add additional context in comments.

Comments

1

for

with open('students.json','w') as file:
    json.dump(out,file,indent=2)

you need to change the 'w' to 'a'

to append the file

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.