Come stampare un file JSON in Python
Il contenuto del file JSON potrebbe essere disordinato se lo si legge sulla stringa o lo si load.
Per esempio, in un file JSON ,
[{"foo": "Etiam", "bar": ["rhoncus", 0, "1.0"]}]
Se lo load e poi lo print.
import json
with open(r"C:\test\test.json", "r") as f:
json_data = json.load(f)
print(json_data)
[{"foo": "Etiam", "bar": ["rhoncus", 0, "1.0"]}]
Il risultato è ben leggibile rispetto al formato standard che vediamo normalmente.
[
{
"foo": "Etiam",
"bar": [
"rhoncus",
0,
"1.0"
]
}
]
Metodo json.dumps
La funzione json.dumps() serializza il dato obj ad una str formattata in JSON.
Dobbiamo dare un numero intero positivo al parametro keyword indent nella funzione json.dumps() per stampare il obj con il livello di rientro dato. Se ident è impostato a 0, inserirà solo nuove righe.
import json
with open(r"C:\test\test.json", "r") as f:
json_data = json.load(f)
print(json.dumps(json_data, indent=2))
[{"foo": "Etiam", "bar": ["rhoncus", 0, "1.0"]}]
Metodo pprint
Il modulo pprint permette di stampare strutture dati Python. Il modulo pprint.pprint stampa un oggetto Python in un flusso seguito da una nuova linea.
import json
import pprint
with open(r"C:\test\test.json", "r") as f:
json_data = f.read()
json_data = json.loads(json_data)
pprint.pprint(json_data)
Il contenuto dei dati del file JSON sarà stampato in modo grazioso. E si può anche definire il trattino assegnando il parametro indent.
pprint.pprint(json_data, indent=2)
pprint tratta le singole ' e le doppie virgolette " in modo identico, ma JSON utilizza solo " quindi il contenuto del file pprinted JSON non può essere salvato direttamente in un file.
In caso contrario, il nuovo file non sarà analizzato come formato JSON valido.
Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.
LinkedIn Facebook