JSON es un formato de texto que permite representar cualquier estructura de datos.
La serialització i la deserialització JSON són els processos de conversió de dades JSON a i des d'altres formats, com ara objectes o strings de Python, per transmetre o emmagatzemar les dades.
A continuació tens un exemple em que serialitzem un objecte Python a un string JSON.
Crea el fitxer data.py
:
import json
data = {
"email": None,
"name": "John Doe",
"age": 42.5,
"married": True,
"children": ["Alice", "Bob"],
}
text = json.dumps(data, indent=4, sort_keys=True)
print(text)
Executem el fitxer:
$ python3 data.py
{
"age": 42.5,
"children": [
"Alice",
"Bob"
],
"email": null,
"married": true,
"name": "John Doe"
}
Pots veure que el resultat és un string de Python formatejat segons les regles gramaticals de JSON.
Funcions comunes
A continuació es mostrens algunes funcions comunes de la llibreria json que s'utilitzen per a la serialització i la deserialització.
json.dumps()
Aquesta funció s'utilitza per serialitzar un objecte Python en una string JSON.
La funció dumps()
pren un sol argument, l'objecte Python, i retorna una string JSON.
Aquí tens un exemple: import json
# Python object to JSON string
python_obj = {'name': 'John', 'age': 30}
json_string = json.dumps(python_obj)
print(json_string)
# output: {"name": "John", "age": 30}
json.loads()
Aquesta funció s'utilitza per un "parse" d’un srting JSON en un objecte Python.
La funció loads()
pren un sol argument, el string JSON, i retorna un objecte Python.
Aquí tens un exemple:
import json
# JSON string to Python object
json_string = '{"name": "John", "age": 30}'
python_obj = json.loads(json_string)
print(python_obj)
# output: {'name': 'John', 'age': 30}
json.dump()
Aquesta funció s'utilitza per serialitzar un objecte Python i escriure'l en un fitxer JSON.
La funció dump()
pren dos arguments, l'objecte Python i l'objecte fitxer.
Aquí tens un exemple:
import json
# serialize Python object and write to JSON file
python_obj = {'name': 'John', 'age': 30}
with open('data.json', 'w') as file:
json.dump(python_obj, file)
json.load()
Aquesta funció s'utilitza per llegir un fitxer JSON i analitzar-ne el contingut en un objecte Python.
La funció load() pren un sol argument, l'objecte fitxer, i retorna un objecte Python.
Aquí tens un exemple:
import json
# read JSON file and parse contents
with open('data.json', 'r') as file:
python_obj = json.load(file)
print(python_obj)
# output: {'name': 'John', 'age': 30}
AEMET
A continuació tens un codi que utilitza les llibreries requests i json per fer una sol·licitud a l'AEMET i recuperar dades:
import requests
import json
municipio = "08019"
key = "eyJhbGciOiJIUzI1NiJ9..." # Utlitza la teva API Key
url = f"https://opendata.aemet.es/opendata/api/prediccion/especifica/municipio/diaria/{municipio}/?api_key={key}"
response = requests.get(url)
if response.status_code == 200:
data = json.loads(response.text)
print(data["datos"])
else:
print(f"Error retrieving data, status code: {response.status_code}")
-
La línia
requests.get(url)
fa la sol·licitud real i emmagatzema la resposta a la variableresponse
. -
La línia
if response.status_code == 200:
comprova si el codi de resposta és 200, la qual cosa significa que la sol·licitud ha tingut èxit. -
Si la sol·licitud té èxit, el codi carrega el text de resposta en un diccionari de Python mitjançant el mètode
json.loads()
i l'emmagatzema a la variabledata
.
Si executes el codi tens la URL on estan les dades meteorològiques:
$ python3 aemet.py
https://opendata.aemet.es/opendata/sh/a5a38371
Modifica el codi perquè consulti "datos"
i torni la probabilitat de precipitació:
import requests
import json
municipio = "08019"
key = "eyJhbGciOiJIUzI1NiJ9..."
url = f"https://opendata.aemet.es/opendata/api/prediccion/especifica/municipio/diaria/{municipio}/?api_key={key}"
response = requests.get(url)
if response.status_code == 200:
data = json.loads(response.text)
datos = data["datos"]
else:
print(f"Error retrieving data, status code: {response.status_code}")
exit
response = requests.get(datos)
if response.status_code == 200:
data = json.loads(response.text)
data = data[0]["prediccion"]["dia"][0]["probPrecipitacion"]
print(json.dumps(data, indent=4))
else:
print(f"Error retrieving data, status code: {response.status_code}")
exit
Resultat:
[
{
"value": 0,
"periodo": "00-24"
},
...
]