Python - JSON

JSON és un format de text que permet representar qualsevol estructura de dades.

Introducció

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

Terminal window
$ 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 mostren 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 variable response.

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

Si executes el codi tens la URL on estan les dades meteorològiques:

Terminal window
$ python3 aemet.py
https://opendata.aemet.es/opendata/sh/a5a38371

Modifica el codi perquè consulti "datos" i torni la probabilitat de precipitació:

Impressió bonica de JSON

Pots utilitzar el mètode dumps() per obtenir una string JSON amb un format “bonic”.

import json
json_data = '[{"ID":10,"Name":"Pankaj","Role":"CEO"},' \
'{"ID":20,"Name":"David Lee","Role":"Editor"}]'
json_object = json.loads(json_data)
json_formatted_str = json.dumps(json_object, indent=2)
print(json_formatted_str)

Això mostra el JSON formatat:

[
{
"ID": 10,
"Name": "Pankaj",
"Role": "CEO"
},
{
"ID": 20,
"Name": "David Lee",
"Role": "Editor"
}
]
  • Primer, utilitzes json.loads() per crear l’objecte JSON a partir del string JSON.

  • El mètode json.dumps() rep l’objecte JSON i retorna una string amb format JSON. El paràmetre indent defineix el nivell de sagnat per al string formatat.

  • How to Pretty Print JSON in Python