Get started learning Python with DataCamp's free Intro to Python tutorial. Learn Data Science by completing interactive coding challenges and watching videos by expert instructors. Start Now!

This site is generously supported by DataCamp. DataCamp offers online interactive Python Tutorials for Data Science. Join 11 million other learners and get started learning Python for data science today!

Good news! You can save 25% off your Datacamp annual subscription with the code LEARNPYTHON23ALE25 - Click here to redeem your discount

Serializzazione


Python fornisce librerie JSON integrate per codificare e decodificare JSON.

In Python 2.5, si utilizza il modulo simplejson, mentre in Python 2.7 si utilizza il modulo json. Poiché questo interprete utilizza Python 2.7, utilizzeremo json.

Per utilizzare il modulo json, deve essere prima importato:

Esistono due formati base per i dati JSON. O in una stringa o nella struttura dati oggetto. La struttura dati oggetto, in Python, consiste in liste e dizionari annidati l'uno nell'altro. La struttura dati oggetto consente di utilizzare i metodi Python (per liste e dizionari) per aggiungere, elencare, cercare e rimuovere elementi dalla struttura dati. Il formato Stringa è principalmente utilizzato per trasferire i dati in un altro programma o caricarli in una struttura dati.

Per caricare JSON indietro in una struttura dati, utilizzare il metodo "loads". Questo metodo prende una stringa e la trasforma nuovamente nella struttura dati json:

Per codificare una struttura dati in JSON, utilizzare il metodo "dumps". Questo metodo prende un oggetto e restituisce una stringa:

Python supporta un metodo proprietario di serializzazione dei dati di Python chiamato pickle (e un'alternativa più veloce chiamata cPickle).

Puoi usarlo esattamente nello stesso modo.

L'obiettivo di questo esercizio è stampare la stringa JSON con la coppia chiave-valore "Me": 800 aggiunta ad essa.

Exercise--------

This site is generously supported by DataCamp. DataCamp offers online interactive Python Tutorials for Data Science. Join over a million other learners and get started learning Python for data science today!

Previous Tutorial Next Tutorial Take the Test
Copyright © learnpython.org. Read our Terms of Use and Privacy Policy