How can I modify the values of json file using python? so my json file is:
JavaScript
x
17
17
1
{
2
"roll no": "210",
3
"school": "DAP",
4
"city": "Delhi",
5
"hobbies": [
6
{
7
"dance": "yes"
8
},
9
{
10
"singing": "yes"
11
},
12
{
13
"travel": "yes"
14
},
15
]
16
}
17
so this is my json
and I want to replace the values like:
roll no= 211 and travel=”no” ,singing=”no”
I have tried:
JavaScript
1
13
13
1
with open("student.json","r") as file:
2
data=json.load(file)
3
data["roll no"]= "211"
4
5
for x in data:
6
x["hobbies"]["singing"]="no"
7
x["hobbies"]["travel"]="no"
8
9
10
with open("student.json","w") as file:
11
12
json.dump(data,file,indent=4)
13
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:
JavaScript
1
17
17
1
{
2
"roll no": "211",
3
"school": "DAP",
4
"city": "Delhi",
5
"hobbies": [
6
{
7
"dance": "yes"
8
},
9
{
10
"singing": "no"
11
},
12
{
13
"travel": "no"
14
},
15
]
16
}
17
Advertisement
Answer
Here is how i have updated hobbies for new roll number
JavaScript
1
30
30
1
import json
2
3
json_data = '''{
4
"roll no": "210",
5
"school": "DAP",
6
"city": "Delhi",
7
"hobbies": [
8
{
9
"dance": "yes"
10
},
11
{
12
"singing": "yes"
13
},
14
{
15
"travel": "yes"
16
}
17
]
18
}
19
'''
20
21
data = json.loads(json_data)
22
23
data["roll no"] = "211"
24
for hobby in data["hobbies"]:
25
for upd_hobby in ["singing", "travel"]:
26
if upd_hobby in hobby:
27
hobby[upd_hobby] = "no"
28
29
print(json.dumps(data, indent=4))
30
Output:
JavaScript
1
17
17
1
{
2
"roll no": "211",
3
"school": "DAP",
4
"city": "Delhi",
5
"hobbies": [
6
{
7
"dance": "yes"
8
},
9
{
10
"singing": "no"
11
},
12
{
13
"travel": "no"
14
}
15
]
16
}
17