Attention: Here be dragons
This is the latest
(unstable) version of this documentation, which may document features
not available in or compatible with released stable versions of Godot.
Checking the stable version of the documentation...
JSON
Eredita: Resource < RefCounted < Object
Classe di supporto per la creazione e l'analisi dei dati JSON.
Descrizione
La classe JSON consente di convertire tutti i tipi di dati da e a una stringa JSON. Ciò è utile per la serializzazione dei dati, ad esempio per salvarli in un file o inviarli in rete.
stringify() serve per convertire qualsiasi tipo di dati in una stringa JSON.
parse() serve per convertire qualsiasi JSON esistente in una Variant che può essere utilizzata all'interno di Godot. Se elaborato correttamente, usa data per recuperare il Variant e usa @GlobalScope.typeof() per verificare se il tipo della variante è quello previsto. Gli oggetti JSON sono convertiti in un Dictionary, ma i dati JSON possono essere utilizzati per archiviare Array, numeri, String e persino solo un valore booleano.
var data_to_send = ["a", "b", "c"]
var json_string = JSON.stringify(data_to_send)
# Salva i dati
# ...
# Ricava i dati
var json = JSON.new()
var error = json.parse(json_string)
if error == OK:
var data_received = json.data
if typeof(data_received) == TYPE_ARRAY:
print(data_received) # Stampa l'array
else:
print("Dati inaspettati")
else:
print("Errore di analisi JSON: ", json.get_error_message(), " in ", json_string, " alla riga ", json.get_error_line())
Alternativamente, è possibile elaborare le stringhe attraverso il metodo statico parse_string(), ma senza poter gestire gli errori.
var data = JSON.parse_string(json_string) # Restituisce null se l'elaborazione non riesce.
Nota: Entrambi i metodi di elaborazione non sono completamente conformi alle specifiche JSON:
Le virgole finali in array o oggetti sono ignorate, invece di causare un errore di elaborazione.
I caratteri di nuova riga e tabulazione sono accettati nei letterali di stringa e sono trattati come le corrispondenti sequenze di escape
\ne\t.I numeri sono elaborati attraverso String.to_float() che è generalmente più permissivo rispetto alle specifiche JSON.
Alcuni errori, come le sequenze Unicode non valide, non causano un errore di elaborazione. Invece, la stringa viene ripulita e un errore viene registrato nella console.
Proprietà
|
Metodi
from_native(variant: Variant, full_objects: bool = false) static |
|
get_error_line() const |
|
get_error_message() const |
|
get_parsed_text() const |
|
parse_string(json_string: String) static |
|
stringify(data: Variant, indent: String = "", sort_keys: bool = true, full_precision: bool = false) static |
|
to_native(json: Variant, allow_objects: bool = false) static |
Descrizioni delle proprietà
Contiene i dati JSON elaborati sotto forma di Variant.
Descrizioni dei metodi
Variant from_native(variant: Variant, full_objects: bool = false) static 🔗
Converte un tipo nativo del motore in un valore conforme a JSON.
Come predefinito, gli oggetti vengono ignorati per motivi di sicurezza, a meno che full_objects non sia true.
È possibile convertire un valore nativo in una stringa JSON in questo modo:
func encode_data(value, full_objects = false):
return JSON.stringify(JSON.from_native(value, full_objects))
Restituisce 0 se l'ultima chiamata a parse() ha avuto successo, oppure il numero di riga in cui l'elaborazione è fallita.
String get_error_message() const 🔗
Restituisce una stringa vuota se l'ultima chiamata a parse() ha avuto successo, oppure il messaggio di errore se è fallita.
String get_parsed_text() const 🔗
Restituisce il testo elaborato da parse() (richiede di passare keep_text a parse()).
Error parse(json_text: String, keep_text: bool = false) 🔗
Tenta di analizzare il testo in JSON (json_text) fornito.
Restituisce una delle costanti di Error. Se l'elaborazione ha avuto successo, restituisce @GlobalScope.OK e il risultato può essere recuperato tramite data. In caso contrario, utilizza get_error_line() e get_error_message() per identificare l'origine dell'errore.
Variazione non statica di parse_string(), se si desidera una gestione personalizzata degli errori.
L'argomento facoltativo keep_text indica al parser di conservare una copia del testo originale. Questo testo può essere ottenuto in seguito tramite la funzione get_parsed_text() e viene utilizzato quando si salva la risorsa (invece di generare nuovo testo da data).
Variant parse_string(json_string: String) static 🔗
Tenta di elaborare la stringa in JSON json_string e restituisce i dati elaborati. Restituisce null se l'elaborazione non riesce.
String stringify(data: Variant, indent: String = "", sort_keys: bool = true, full_precision: bool = false) static 🔗
Converts a Variant var to JSON text and returns the result. Useful for serializing data to store or send over the network.
Note: The JSON specification does not define integer or float types, but only a number type. Therefore, converting a Variant to JSON text will convert all numerical values to float types.
Note: If full_precision is true, when stringifying floats, the unreliable digits are stringified in addition to the reliable digits to guarantee exact decoding.
The indent parameter controls if and how something is indented; its contents will be used where there should be an indent in the output. Even spaces like " " will work. \t and \n can also be used for a tab indent, or to make a newline for each indent respectively.
Warning: Non-finite numbers are not supported in JSON. Any occurrences of @GDScript.INF will be replaced with 1e99999, and negative @GDScript.INF will be replaced with -1e99999, but they will be interpreted correctly as infinity by most JSON parsers. @GDScript.NAN will be replaced with null, and it will not be interpreted as NaN in JSON parsers. If you expect non-finite numbers, consider passing your data through from_native() first.
Example output:
## JSON.stringify(my_dictionary)
{"name":"my_dictionary","version":"1.0.0","entities":[{"name":"entity_0","value":"value_0"},{"name":"entity_1","value":"value_1"}]}
## JSON.stringify(my_dictionary, "\t")
{
"name": "my_dictionary",
"version": "1.0.0",
"entities": [
{
"name": "entity_0",
"value": "value_0"
},
{
"name": "entity_1",
"value": "value_1"
}
]
}
## JSON.stringify(my_dictionary, "...")
{
..."name": "my_dictionary",
..."version": "1.0.0",
..."entities": [
......{
........."name": "entity_0",
........."value": "value_0"
......},
......{
........."name": "entity_1",
........."value": "value_1"
......}
...]
}
Variant to_native(json: Variant, allow_objects: bool = false) static 🔗
Converte un valore conforme a JSON in che è stato creato con from_native() in tipi nativi del motore.
Come predefinito, gli oggetti vengono ignorati per motivi di sicurezza, a meno che allow_objects non sia true.
È possibile convertire una stringa JSON in un valore nativo in questo modo:
func decode_data(string, allow_objects = false):
return JSON.to_native(JSON.parse_string(string), allow_objects)