Adding values to JSON file in python - python

I currently have a son file created called "newsuser.json". I am trying to get a users name to be saved to the son file each time a new user is added. I can currently get a user to be saved, but when another user is added the previous user is overwritten, resulting in only having one user stored.
I am trying to get me JSON file to look like this:
{
"users":[
{
"name":"test1"
},
{
"name":"test2"
}
]
}
Instead my output looks like:
{"name": "test1"}
Here is my code for creating a JSON object and saving to "newsuser.json"
import json
userName = form.getvalue('userName')
newDict = {"name": "test1"}
with open("cgi-bin/newsuser.json") as f:
data = json.load(f)
data.update(newDict)
with open("cgi-bin/newsuser.json", "w") as f:
json.dump(data, f)
Does anyone have ideas how I can get a JSON file to print my objects under "user" and not overwrite each entry?

just replace 'w' with 'a' like below
with open("cgi-bin/newsuser.json", "a") as f:
json.dump(data, f)

Related

How to save data

I'm trying to save data with Python and Json, Im trying to have it save like this
"UserID" {
"Code":12123
}
But I cannot get anywhere near this look or working order. Here is the code that is saving to the Json.
with open('data.json') as f:
data = json.load(f)
data.append([str(ctx.author.id)]["Code"])
with open('data.json','w') as f:
json.dump(data, f)
How can I get it to save like my example above so I can be able to get the code via the userid when fetching the codes.

Python Trying to read json file and print specific information

So, I need to load specific "questions" from a json file, when I loaded it, it just shows this: {'Question1': 'What is your name?'}. How do I make it just show "What is your name"?
My Code:
import json
with open("main.json", "r") as f:
responses = json.load(f)
print(responses)
Json File:
{
"Question1": "What is your name?"
}
import json
with open("main.json", "r") as f:
responses = json.load(f)
print(responses["Question1"])
In this approach all questions from JSON file will be read by json.load(f) instruction and stored within dictionary called responses. Keys of this dict will be question names f.e "Question1" and values will be question contents f.e "What is your name?".
When we have more questions we can iterate over them:
import json
with open("main.json", "r") as f:
responses = json.load(f)
for question_name, question_content in responses.items():
print(question_content)
So for this JSON file:
{
"Question1": "What is your name?",
"Question2": "What is your age?"
}
it will print:
What is your name?
What is your age?

How to read a json file, find a key and bring the related data as object on Python?

I'm kinda new to Python and hence learning by doing, so here I am asking for some heads up.
I need to store values in a JSON file, and later in the next execution check first if the user already requested access into the system to provide the proper returns.
So basically my json file will be:
{instance_id : 1111 {'username':'Dummy_User','email':'dummy#user.com','domain':'local','role':'admin','instance':'production','group':'administrators','state':'failed','description':'User Dummy_User is already a member of group administrators'}
},
{instance_id : 2222 {'username':'Dummy_User1','email':'dummy#user.com','domain':'local','role':'admin','instance':'production','group':'administrators','state':'success','description':'User Dummy_User1 added to the administrators group'}
}
I need to be able to query it by instance_id and get as return all of the fields, or a particular one.
Example:
result = checkJson(1111)
print (result.state + " - " + result.description)
>> failed - User Dummy_User is already a member of group administrators
What I'm currently doing: I'm writing the file using "with open" funcion but it is not separating the "objects" by comma in the file, hence it is not being recognizable as a valid json later
def write_json(self, data, filename):
with open(filename,'r+') as f:
json_data = json.load(f)
json_data.update(data)
f.seek(0)
json.dump(json_data, f)
Any thoughts on the best way to do that?
Thank you in advance!
I figured. As per my example, I could get it done by:
Writing in the json:
userInput = {id : {"username":username,"adgroup":adgroup}}
filename = "path\to\file.json"
with open(filename,"r+") as f:
json_data = json.load(f)
json_data.update(data)
f.seek(0)
json.dump(json_data, f)
This will create an object of userInput and add to the json within the agregate structure.
Later, to read this json I used:
jsonFile = "path\to\file.json"
with open(jsonFile) as access:
data = json.load(access)
instance = data[id]['username']
name = data[id]['adgroup']
where ID is the ID stored in the JSON to identify that object you saved before.

How to change the JSON file contents for the below json file

I have a json file say 1.control_file.txt and i need to chnage it's values every now and then,so say i have a ticket Sample1 and with that i need to change the date field, also other fields are required sometimes.
So suppose say i fetched the ticket no as user input and so how do i change the ticket field together with suppose say a given start and end date.
Also the exporter names tag in the json file should be changeable..
Can any on suggest me on how do i do that using shell or python?
Fields i am taking as user input user,ticket,startdate,end_date and sample_names...
"user": "dexter",
"ticket": "Sample1",
"start_date": "2018-07-02",
"end_date": "2019-07-02",
"sample_names": [
"Demo1exp1",
"Demo2exp2",
"Demo3exp3",
"Demo4exp4",
"Demo5exp5",
"Demo6exp6",
"Demo7exp7",
"Demo8exp8",
"Demo9exp9"
]
}```
This snippet of code is probably what you need
import json
with open('data.txt') as json_file:
data = json.load(json_file)
data['start_date'] = "2018-07-03"
with open('data.txt', 'w') as outfile:
json.dump(data, outfile)

How to update a JSON file by using Python?

I am using Python and I have a JSON file in which I would like to update a value related to a given key. That is, I have the my_file.json containing the following data
{"a": "1", "b": "2", "c": "3"}
and I would like to just change the value related to the b key from 2 to 9 so that the updated file look as like:
{"a": "1", "b": "9", "c": "3"}
How can I make that?
I tried the following but without success (the changes are not saved to the file):
with open('my_file.json', 'r+') as f:
json_data = json.load(f)
json_data['b'] = "9"
f.close()
You did not save the changed data at all. You have to first load, then modify, and only then save. It is not possible to modify JSON files in-place.
with open('my_file.json', 'r') as f:
json_data = json.load(f)
json_data['b'] = "9"
with open('my_file.json', 'w') as f:
f.write(json.dumps(json_data))
You may also do this:
with open('my_file.json', 'r+') as f:
json_data = json.load(f)
json_data['b'] = "9"
f.seek(0)
f.write(json.dumps(json_data))
f.truncate()
If you want to make it safe, you first write the new data into a temporary file in the same folder, and then rename the temporary file onto the original file. That way you will not lose any data even if something happens in between.
If you come to think of that, JSON data is very difficult to change in-place, as the data length is not fixed, and the changes may be quite significant.
You are almost there, you only have to write the updated json_data back to the file. Get rid of f.close(), as the with statement will ensure that the file is closed. Then, issue
with open('my_file.json', 'w') as f:
f.write(json.dumps(json_data))
This is simplest way to do the json file updation/writing.
where you are creating instance of json file as 'f' and the writing the 'data' into the json file,
#write json file
with open('data.json', 'w') as f:
json.dump(data, f)
#Read json file
with open('data.json', 'r') as f:
json.load(data, f)
Open the file and store in one variable all the content using json.load function
Update your key stored in the previous variable
Open the file another time and update your content with the variable updated
def updateJsonFile():
jsonFile = open("my_file.json", "r") # Open the JSON file for reading
data = json.load(jsonFile) # Read the JSON into the buffer
jsonFile.close() # Close the JSON file
## Working with buffered content
data["b"] = "9"
## Save our changes to JSON file
jsonFile = open("my_file.json", "w+")
jsonFile.write(json.dump(data))
jsonFile.close()

Categories