How do I add information to an existing json file using python?

Asked

Viewed 177 times

-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:

erro que aparece com a execução do código

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:

arquivo json

(I inserted by hand just to show, I can’t leave this way running the code)

But you’re getting that way:

json inválido

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

  • 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.

  • 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

  • Ask a sample of the file data and the data you want to enter.

  • 2

    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)

  • the answers are in another programming language, and I only know python. How can I make a list of objects in json using python?

  • Just put them on a list: lista = [objeto1, objeto2, objeto3] - or else lista = [] and then lista.append(objeto1), lista.append(objeto2), etc. And then save the list in the file, passing it to json.dump (and using the suggested methods in the answer already indicated to avoid the problems of overwriting the file)

  • updated the code with the suggestions you gave me, but still gives error...

  • 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 ...

Show 4 more comments

1 answer

0

I want to thank everyone who has devoted a few minutes of their time to help me, today I finally got my code running to save the data the way I need it. So, not to leave future visitors unanswered I will tell you my solution:

I reworked the function of loading and saving the files and left them that way:

def salvar_dados(nomedojson, file):
with open(nomedojson, "w", encoding="utf-8") as dados:
    salvando = json.dump(file, dados, indent=2, separators=(",", ": "), sort_keys=True)
    return salvando

def carregar_dados(nomedojson):
if isfile(nomedojson):  # Verifica se o arquivo já existe, se sim, o json será carregado
    with open(nomedojson, "r", encoding="utf-8") as dados:
        return json.load(dados)
else:  # Se o json ainda não existe, a função cria e retorna uma lista
    temporario = []
    return temporario

Then I make the function load the file before the whole program start:

try:
    dados_p = carregar_dados("Banco de dados1.json")
    dados_s = carregar_dados("Banco de dados2.json")
    dados_c = carregar_dados("Banco de dados3.json")
    # Se os jsons ainda não existirem, uma lista para cada um será retornada
except Exception as erro:
    print("Ocorreu um erro durante o carregamento: ", erro)

After loading the jsons (or lists), a main menu appears, where the user can register and query the json files.

A very important detail is to use the same variables "dados_p", "dados_s" and "dados_c" to effect and save changes to json files using the append command. Ex: "dados_p.append(file)"

It took me a long time to learn how to do this kind of thing. I hope that I have been able to be clear in my question and in my answer to the question. Once again, many thanks to those who have dedicated their attention to help me! I hope also to be able to help those with the same problem.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.