I'm currently writing a program in Python that reads and edits JSON files as need while going through different operations.
My current JSON I'm testing with:
{
"Servant": [
{
"name": "Jeanne Alter Santa Lily",
"f_class": "Lancer.png",
"claim": false,
"appear": true,
"pic_url": "test.png",
"line": "I'm Jeanne! It's a bit early for Christmas but, let's do
our best together! By the way, do you know how this Sled
moves?"
},
{
"name": "Artoria",
"f_class": "Saber.png",
"claim": false,
"appear": true,
"pic_url": "test1.png",
"line": "I ask of you. Are you my Master?"
}
]
}
Within my program you will have the ability to claim a person and the "claim" boolean in the JSON would change from False to True.
My question is who would I go about editing a specific value deep into the JSON? I can't figure out how to go into this JSON and edit a specific value of a key in Python. I will later implement your solution with a larger JSON of the same format with over 100 entries.
Thank you in advance.
Json files are same as dictionaries can be accessed the same way
We want to select claim inside the json file so we might use
File_name[“servant”][0][“claim”]
So that way we can make any changes we want by accessing the file parts like dictionaries by specifying their names.
Test.json:
{
"Servant": [
{
"name": "Jeanne Alter Santa Lily",
"f_class": "Lancer.png",
"claim": false,
"appear": true,
"pic_url": "test.png",
"line": "I'm Jeanne! It's a bit early for Christmas but, let's do
our best together! By the way, do you know how this Sled
moves?"
},
{
"name": "Artoria",
"f_class": "Saber.png",
"claim": false,
"appear": true,
"pic_url": "test1.png",
"line": "I ask of you. Are you my Master?"
}
]
}
Code:
import json #importing json module which is used to handle json files
with open("test.json", "r+") as jsonFile: #opening the jsonfile in read+ mode able to read and write back the changes
data = json.load(jsonFile) #loading the file with json load to able to handle json
inp=input("enter the name you want to change : ") #taking input for what name you want to change
for i in data["Servant"]: #iterating the json file to find the required one
if(i["name"]==inp): #if found the required to make changes
i["claim"]=True #making changes
jsonFile.seek(0) # rewind to start
json.dump(data, jsonFile) #updating the json file
jsonFile.truncate() #closing the file
output:

The json file was updated after the execution of the program.
Code screenshot:

I'm currently writing a program in Python that reads and edits JSON files as need while...