logo

json.dumps() in Python

JSON è un acronimo che sta per JavaScript Object Notation. Nonostante il nome, JSON è un formato indipendente dalla lingua che viene comunemente utilizzato per trasmettere dati tra sistemi e, occasionalmente, archiviare dati. I programmi scritti in Python, così come molti altri linguaggi di programmazione, possono acquisire dati in formato JSON e serializzare i dati in memoria nel formato JSON. Pitone supporta JSON tramite un pacchetto integrato chiamato json. Per utilizzare questa funzionalità, importa il pacchetto json nello script o nel modulo Python in cui desideri serializzare o deserializzare i tuoi dati. JSON utilizza coppie chiave-valore delimitate da virgole contenute tra virgolette doppie e separate da due punti. Il corpo di un file JSON può essere delimitato da parentesi graffe { } o parentesi quadre [] (note anche come parentesi in alcune impostazioni locali). Il formato JSON sembra essere simile al dizionario in Python, ma le specifiche del formato JSON presentano differenze significative, quindi fai attenzione quando lavori con entrambi i formati.

Nota: Per ulteriori informazioni, fare riferimento a Leggi, Scrivi e analizza JSON utilizzando Python



Json.dumps()

La funzione json.dumps() convertirà un sottoinsieme di oggetti Python in una stringa json. Non tutti gli oggetti sono convertibili e potrebbe essere necessario creare un dizionario di dati che si desidera esporre prima della serializzazione in JSON.

Sintassi:
json.dumps(obj, *, skipkeys=False, aware_ascii=True, check_circular=True,allow_nan=True, cls=Nessuno, indent=Nessuno, separatori=Nessuno, default=Nessuno, sort_keys=False, **kw)
parametri:
oggetto: Serializza obj come flusso formattato JSON
salta i tasti: Se skipkeys è True (predefinito: False), le chiavi dict che non sono di tipo base (str, int, float, bool, None) verranno ignorate invece di sollevare un TypeError.
garantire_ascii: Se Guarantee_ascii è True (impostazione predefinita), è garantito che l'output contenga l'escape di tutti i caratteri non ASCII in entrata. Se Guarantee_ascii è False, questi caratteri verranno emessi così come sono.
check_circolare: Se check_circular è False (impostazione predefinita: True), il controllo del riferimento circolare per i tipi di contenitore verrà ignorato e un riferimento circolare risulterà in un OverflowError (o peggio).
consent_in: Se consent_nan è False (impostazione predefinita: True), sarà un ValueError serializzare valori float fuori intervallo (nan, inf, -inf) nel rigoroso rispetto della specifica JSON. Se consent_nan è True, verranno utilizzati i relativi equivalenti JavaScript (NaN, Infinity, -Infinity).
trattino: Se il rientro è un numero intero o una stringa non negativo, gli elementi dell'array JSON e i membri dell'oggetto verranno stampati con quel livello di rientro. Un livello di rientro pari a 0, negativo o inserirà solo nuove righe. Nessuno (l'impostazione predefinita) seleziona la rappresentazione più compatta. L'uso di un rientro intero positivo fa rientrare tanti spazi per livello. Se il rientro è una stringa (come ), quella stringa viene utilizzata per rientrare ogni livello.
separatori: Se specificati, i separatori dovrebbero essere una tupla (item_separator, key_separator). Il valore predefinito è (‘, ‘, ‘: ‘) se il rientro è Nessuno e (‘, ‘, ‘: ‘) altrimenti. Per ottenere la rappresentazione JSON più compatta, dovresti specificare (',',':') per eliminare gli spazi bianchi.
predefinito: Se specificato, default dovrebbe essere una funzione che viene chiamata per oggetti che non potrebbero altrimenti essere serializzati. Dovrebbe restituire una versione codificabile JSON dell'oggetto o sollevare un TypeError. Se non specificato, viene sollevata l'eccezione TypeError.
sort_keys: Se sort_keys è True (predefinito: False), l'output dei dizionari verrà ordinato per chiave.

Esempio 1: Passare il dizionario Python alla funzione json.dumps() restituirà una stringa.



Python3

sottostringa della stringa Java






import> json> # Creating a dictionary> Dictionary>=>{>1>:>'Welcome'>,>2>:>'to'>,> >3>:>'Geeks'>,>4>:>'for'>,> >5>:>'Geeks'>}> > # Converts input dictionary into> # string and stores it in json_string> json_string>=> json.dumps(Dictionary)> print>(>'Equivalent json string of input dictionary:'>,> >json_string)> print>(>' '>)> # Checking type of object> # returned by json.dumps> print>(>type>(json_string))>

>

>

Produzione

Stringa json equivalente del dizionario: {1: Benvenuto, 2: a, 3: Geeks, 4: for, 5: Geeks}

Esempio n.2: Impostando skipkeys su True (predefinito: False) saltiamo automaticamente i tasti che non sono di tipo base.

Python3




import> json> Dictionary>=>{(>1>,>2>,>3>):>'Welcome'>,>2>:>'to'>,> >3>:>'Geeks'>,>4>:>'for'>,> >5>:>'Geeks'>}> # Our dictionary contains tuple> # as key, so it is automatically> # skipped If we have not set> # skipkeys = True then the code> # throws the error> json_string>=> json.dumps(Dictionary,> >skipkeys>=> True>)> print>(>'Equivalent json string of dictionary:'>,> >json_string)>

>

>

Produzione

Stringa json equivalente del dizionario: {2: to, 3: Geeks, 4: for, 5: Geeks}

Esempio n.3:

quadro di raccolta Java

Python3




import> json> # We are adding nan values> # (out of range float values)> # in dictionary> Dictionary>=>{(>1>,>2>,>3>):>'Welcome'>,>2>:>'to'>,> >3>:>'Geeks'>,>4>:>'for'>,> >5>:>'Geeks'>,>6>:>float>(>'nan'>)}> # If we hadn't set allow_nan to> # true we would have got> # ValueError: Out of range float> # values are not JSON compliant> json_string>=> json.dumps(Dictionary,> >skipkeys>=> True>,> >allow_nan>=> True>)> print>(>'Equivalent json string of dictionary:'>,> >json_string)>

>

>

Produzione :

Stringa json equivalente del dizionario: {2: to, 3: Geeks, 4: for, 5: Geeks, 6: NaN}

Esempio n.4:

Python3




import> json> Dictionary>=>{(>1>,>2>,>3>):>'Welcome'>,>2>:>'to'>,> >3>:>'Geeks'>,>4>:>'for'>,> >5>:>'Geeks'>,>6>:>float>(>'nan'>)}> # Indentation can be used> # for pretty-printing> json_string>=> json.dumps(Dictionary,> >skipkeys>=> True>,> >allow_nan>=> True>,> >indent>=> 6>)> print>(>'Equivalent json string of dictionary:'>,> >json_string)>

>

>

Produzione:

Equivalent json string of dictionary: { '2': 'to', '3': 'Geeks', '4': 'for', '5': 'Geeks', '6': NaN }>

Esempio n.5:

cambiare nome directory linux

Python3




import> json> Dictionary>=>{(>1>,>2>,>3>):>'Welcome'>,>2>:>'to'>,> >3>:>'Geeks'>,>4>:>'for'>,> >5>:>'Geeks'>,>6>:>float>(>'nan'>)}> # If specified, separators should be> # an (item_separator, key_separator)tuple> # Items are separated by '.' and key,> # values are separated by '='> json_string>=> json.dumps(Dictionary,> >skipkeys>=> True>,> >allow_nan>=> True>,> >indent>=> 6>,> >separators>=>(>'. '>,>' = '>))> print>(>'Equivalent json string of dictionary:'>,> >json_string)>

>

>

Produzione:

Equivalent json string of dictionary: { '2' = 'to'. '3' = 'Geeks'. '4' = 'for'. '5' = 'Geeks'. '6' = NaN }>

Esempio n.6:

Python3




import> json> Dictionary>=>{>'c'>:>'Welcome'>,>'b'>:>'to'>,> >'a'>:>'Geeks'>}> json_string>=> json.dumps(Dictionary,> >indent>=> 6>,> >separators>=>(>'. '>,>' = '>),> >sort_keys>=> True>)> print>(>'Equivalent json string of dictionary:'>,> >json_string)>

>

>

Produzione:

Equivalent json string of dictionary: { 'a' = 'Geeks'. 'b' = 'to'. 'c' = 'Welcome' }>