Escriu per cercar…

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:

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

shell
$ 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
# 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:

python
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}

Estàs llegint una vista prèvia.

Inicia sessió per llegir l'article complet. Qualsevol compte obre 4 articles gratuïts al mes; l'alumnat i el professorat llegeixen les pàgines del seu curs sense límit.

Inicia sessió