I have this function: def SetData(Username, Data):
.
I have a JSON file called "data.json" and want to know the best way to make a value with the person’s "Username" and add the "Data" value to it. I also want to make sure that it will override any existing values with that username. Please note I have never coded with Python and this is my first project, so this is probably a really dumb question.
Thanks!
2
Answers
Your question isn’t dumb at all! Everyone starts somewhere, and I’m here to help. Let’s break down the problem and provide you with a step-by-step solution using Python.
You want to create a function
SetData(Username, Data)
that updates a JSON file (data.json
) with the providedData
for a givenUsername
. Here’s how you can approach this:Data
value for the givenUsername
.Here’s the code to accomplish this:
Please note:
data.json
file in the same directory as your Python script.Remember, when working with code and data, it’s always a good practice to make backups and test thoroughly.
Updated for list type:
If your
data.json
file is a list, and JSON file looks like this:Here’s how you can modify the code:
Please replace the JSON structure and the field names in the code with the actual structure of your
data.json
file. This code will search for the username in the list and update the associated data if the username is found. If not, you can decide whether you want to add a new entry or handle it differently.First of all you need to decide on what the file structure is going to look like – i.e., is it a single JSON object or a list of objects. Then you need to consider what happens if the file doesn’t exist or has an incorrect structure – e.g., not valid JSON
Let’s assume that you want your JSON file to contain a list of JSON objects then: