How can I modify the values of json file using python?
so my json file is:
{
"roll no": "210",
"school": "DAP",
"city": "Delhi",
"hobbies": [
{
"dance": "yes"
},
{
"singing": "yes"
},
{
"travel": "yes"
},
]
}
so this is my json
and I want to replace the values like:
roll no= 211 and travel="no" ,singing="no"
I have tried:
with open("student.json","r") as file:
data=json.load(file)
data["roll no"]= "211"
for x in data:
x["hobbies"]["singing"]="no"
x["hobbies"]["travel"]="no"
with open("student.json","w") as file:
json.dump(data,file,indent=4)
I have tried this but the only change I’m able to doing is roll no,but I’m unable to change the hobbies values
expected output:
{
"roll no": "211",
"school": "DAP",
"city": "Delhi",
"hobbies": [
{
"dance": "yes"
},
{
"singing": "no"
},
{
"travel": "no"
},
]
}
3
Answers
‘hobbies’ is a list of dict so you should write:
Here is how i have updated hobbies for new roll number
Output:
As i said in above comment, you will get an error while passing index as string to list.
See below code
Methode 1 (If the hobbies are hardcoded)
Method 2 (if you want to dynamically include some hobbies to change their state ‘yes’ – ‘no’)