How to save data - python

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.

Related

How to create and open a json file?

Does anybody know why this code doesnt work? We are trying to create a json file and write some information in it. The aim is to create a user account, save the password and name in a json file and then login and go on with other functions. See the code below. Any help appreciated!!
player_data_file = 'player_portfolio.json'
with open(player_data_file, 'r') as f:
if os.stat(player_data_file).st_size == 0:
data = {}
else:
data = json.load(f)
data.update({player_name: {"balance": balance, "portfolio": {}}})
with open(player_data_file, 'w') as f:
json.dump(data, f, indent=4)

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)

Adding values to JSON file in 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)

JSON Line issue when loading from import.io using Python

I'm having a hard time trying to load an API response from import.io into a file or a list.
The enpoint I'm using is https://data.import.io/extractor/{0}/json/latest?_apikey={1}
Previously all my scripts were set to use normal JSON and all was working well, but now hey have decided to use json line, but somehow it seems malformed.
The way I tried to adapt my scripts is to read the API response in the following way:
url_call = 'https://data.import.io/extractor/{0}/json/latest?_apikey={1}'.format(extractors_row_dict['id'], auth_key)
r = requests.get(url_call)
with open(temporary_json_file_path, 'w') as outfile:
json.dump(r.content, outfile)
data = []
with open(temporary_json_file_path) as f:
for line in f:
data.append(json.loads(line))
the problem doing this is that when I check data[0], all of the json file content was dumped in it...
data[1] = IndexError: list index out of range
Here is an example of data[0][:300]:
u'{"url":"https://www.example.com/de/shop?condition[0]=new&page=1&lc=DE&l=de","result":{"extractorData":{"url":"https://www.example.com/de/shop?condition[0]=new&page=1&lc=DE&l=de","resourceId":"23455234","data":[{"group":[{"Brand":[{"text":"Brand","href":"https://www.example.com'
Does anyone have experience with the response of this API?
All other jsonline reads I do from other sources work fine except this one.
EDIT based on comment:
print repr(open(temporary_json_file_path).read(300))
gives this:
'"{\\"url\\":\\"https://www.example.com/de/shop?condition[0]=new&page=1&lc=DE&l=de\\",\\"result\\":{\\"extractorData\\":{\\"url\\":\\"https://www.example.com/de/shop?condition[0]=new&page=1&lc=DE&l=de\\",\\"resourceId\\":\\"df8de15cede2e96fce5fe7e77180e848\\",\\"data\\":[{\\"group\\":[{\\"Brand\\":[{\\"text\\":\\"Bra'
You've got a bug in your code where you are double encoding:
with open(temporary_json_file_path, 'w') as outfile:
json.dump(r.content, outfile)
Try:
with open(temporary_json_file_path, 'w') as outfile:
outfile.write(r.content)

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