-1
I’m trying to create a function to save data in a json file in python and I can’t do it without the old data being overwritten by the new ones (I want the old ones to remain and the new ones to be added soon after).
Nor can I keep the old data together with the new data without json becoming invalid, since "a" mode does not add a comma after the first object before adding the new one...
I’ve been trying to do as I’ve seen in some places: upload the json file, add new content and save it again in the file, but I’m not able to build the function without error.
my function is so with the suggestions of the comments:
def salvar_dados(nomedojson, file):
if not isfile(nomedojson): # Verifica se o arquivo já existe, se não existir ele vai criar
with open(nomedojson, "w", encoding="utf-8") as dados:
lista = []
lista.append(file)
salvando1 = json.dump(lista, dados, indent=2, separators=(",", ": "), sort_keys=True)
return salvando1
else: # condição que atesta que o arquivo já existe e só precisa ser atualizado
with open(nomedojson, "r+", encoding="utf-8") as dados:
carregando = [json.load(dados)] # comando para carregar o arquivo existente
atualizando = carregando.append(file) # comando para supostamente atualizar o conteúdo
salvando2 = json.dump(atualizando, dados, indent=2, separators=(",", ": "), sort_keys=True)
return salvando2
And the following error appears:
data sample:
dic_p = {self.nome_completo[0]+" "+self.nome_completo[1]: {'Nome': self.nome[0], 'Sobrenome': self.sobrenome[0]}}
I wanted it to stay that way:
(I inserted by hand just to show, I can’t leave this way running the code)
But you’re getting that way:
I’ve been trying to solve this problem for 3 days, I’m running out of ideas to test... If anyone can help I appreciate!
In the question suggested above, the first answer is not the most indicated for ending up having the same problem you had (generating an invalid JSON when adding data to the file). I suggest you take a look at the other answer, it seems to me that you need: https://answall.com/a/467156/112052
– hkotsubo
It was exactly in this link that I inspired to change the code to what it is like I presented in this question that I just asked. I can’t do the code exactly as you answered it because I want to add dictionaries inside dictionaries and not questions and answers.
– Suu Kirinus
But the idea is the same, no matter if the dictionary has other dictionaries in it or whatever. From what I understand, you can use exactly the same code there: if
dados
is a dictionary, no matter what is in it, the way to save and update is the same– hkotsubo
Ask a sample of the file data and the data you want to enter.
– Augusto Vasques
Ah, now it’s explained: what you want to save is not a JSON, it’s actually 2 "loose" objects, independent - has explanation here, but to summarize,
{alguma coisa}, {outra coisa}
are 2 loose objects (one containing "something", and the other containing "something else"), so it does not work to save everything as a single JSON. What you could do is put all these different objects in a list (then the file would look like a single JSON, only in an array)– hkotsubo
the answers are in another programming language, and I only know python. How can I make a list of objects in json using python?
– Suu Kirinus
Just put them on a list:
lista = [objeto1, objeto2, objeto3]
- or elselista = []
and thenlista.append(objeto1)
,lista.append(objeto2)
, etc. And then save the list in the file, passing it tojson.dump
(and using the suggested methods in the answer already indicated to avoid the problems of overwriting the file)– hkotsubo
updated the code with the suggestions you gave me, but still gives error...
– Suu Kirinus
I also tried the logic of loading the file’s read-only content with r, transforming the content into JSON, changing the json object in memory with the append, calling the writing mode with w, saving the JSON object overwriting the file, and the result? Null ...
– Suu Kirinus