Skip to content
Advertisement

How to store input values from user in json format?

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)

Advertisement

Answer

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)

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement