I want to read a json file in Python and add content to the file respecting the json format, but I can't manage to do it.
The json file "paises.json":
{
"España": [
{
"Superficie": 505944,
"Población": 47450795
}
],
"Francia": [
{
"Superficie": 675417,
"Población": 67407241
}
]
}
I want to read that file in Python and append new content to it. The code is:
import json
with open("paises.json", "r", encoding="utf-8") as paises:
datos = json.load(paises)
print(datos.keys()) # Show dictionary
nombre_pais = input("\nIndique el nombre del país\n")
nueva_superficie = float(input("\nIndique la superficie\n"))
nueva_poblacion = int(input("\nIndique la Población\n"))
nuevo_contenido = {nombre_pais: {"Superficie": nueva_superficie, "Población": nueva_poblacion}}
datos.update(nuevo_contenido)
print(datos) # Show dictionary with new content
with open("paises.json", "a", encoding="utf-8") as paises:
json.dump(nuevo_contenido, paises)
The result is not what I have expected:
{
"España": [
{
"Superficie": 505944,
"Población": 47450795
}
],
"Francia": [
{
"Superficie": 675417,
"Población": 67407241
}
]
}
{"Portugal": {"Superficie": 92090, "Poblaci\u00f3n": 10295909}}
The formatting is not correct, a comma and a square bracket are missing and the coding of the accents is not ok.
What can I do to correct it?
Thank you
You can't append new data directly to JSON file because it creates incorrect JSON.
(Exception can be when you want to create multi-JSON
file)
With normal JSON you have to:
datos
) from memory to file in "write mode"
, not "append mode"
.with open("paises.json", "w", encoding="utf-8") as paises:
json.dump(datos, paises)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.