JSON

Hereda: Resource < RefCounted < Object

Clase auxiliar para crear y analizar datos JSON.

Descripción

The JSON class enables all data types to be converted to and from a JSON string. This is useful for serializing data, e.g. to save to a file or send over the network.

stringify() is used to convert any data type into a JSON string.

parse() is used to convert any existing JSON data into a Variant that can be used within Godot. If successfully parsed, use data to retrieve the Variant, and use @GlobalScope.typeof() to check if the Variant's type is what you expect. JSON Objects are converted into a Dictionary, but JSON data can be used to store Arrays, numbers, Strings and even just a boolean.

var data_to_send = ["a", "b", "c"]
var json_string = JSON.stringify(data_to_send)
# Save data
# ...
# Retrieve data
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) # Prints the array.
    else:
        print("Unexpected data")
else:
    print("JSON Parse Error: ", json.get_error_message(), " in ", json_string, " at line ", json.get_error_line())

Alternatively, you can parse strings using the static parse_string() method, but it doesn't handle errors.

var data = JSON.parse_string(json_string) # Returns null if parsing failed.

Note: Both parse methods do not fully comply with the JSON specification:

  • Trailing commas in arrays or objects are ignored, instead of causing a parser error.

  • New line and tab characters are accepted in string literals, and are treated like their corresponding escape sequences \n and \t.

  • Numbers are parsed using String.to_float() which is generally more lax than the JSON specification.

  • Certain errors, such as invalid Unicode sequences, do not cause a parser error. Instead, the string is cleaned up and an error is logged to the console.

Propiedades

Variant

data

null

Métodos

Variant

from_native(variant: Variant, full_objects: bool = false) static

int

get_error_line() const

String

get_error_message() const

String

get_parsed_text() const

Error

parse(json_text: String, keep_text: bool = false)

Variant

parse_string(json_string: String) static

String

stringify(data: Variant, indent: String = "", sort_keys: bool = true, full_precision: bool = false) static

Variant

to_native(json: Variant, allow_objects: bool = false) static


Descripciones de Propiedades

Variant data = null 🔗

Contiene los datos JSON analizados en formato Variant.


Descripciones de Métodos

Variant from_native(variant: Variant, full_objects: bool = false) static 🔗

Convierte un tipo de motor nativo en un valor compatible con JSON.

Por defecto, los objetos se ignoran por razones de seguridad, a menos que full_objects sea true.

Puedes convertir un valor nativo en una cadena JSON de esta manera:

func encode_data(value, full_objects = false):
    return JSON.stringify(JSON.from_native(value, full_objects))

int get_error_line() const 🔗

Devuelve 0 si la última llamada a parse() fue exitosa, o el número de línea donde falló el análisis.


String get_error_message() const 🔗

Devuelve una string vacía si la última llamada a parse() fue exitosa, o el mensaje de error si falló.


String get_parsed_text() const 🔗

Devuelve el texto analizado por parse() (requiere pasar keep_text a parse()).


Error parse(json_text: String, keep_text: bool = false) 🔗

Intenta analizar el json_text proporcionado.

Devuelve un Error. Si el análisis fue exitoso, devuelve @GlobalScope.OK y el resultado se puede recuperar usando data. Si no tiene éxito, usa get_error_line() y get_error_message() para identificar la causa del fallo.

Variante no estática de parse_string(), si quieres un manejo de errores personalizado.

El argumento opcional keep_text instruye al analizador a mantener una copia del texto original. Este texto se puede obtener más tarde usando la función get_parsed_text() y se usa al guardar el recurso (en lugar de generar nuevo texto a partir de data).


Variant parse_string(json_string: String) static 🔗

Intenta analizar la json_string proporcionada y devuelve los datos analizados. Devuelve null si el análisis falla.


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 🔗

Convierte un valor compatible con JSON que se creó con from_native() de nuevo a los tipos de motor nativos.

Por defecto, los objetos se ignoran por razones de seguridad, a menos que allow_objects sea true.

Puedes convertir un string JSON de nuevo a un valor nativo así:

func decode_data(string, allow_objects = false):
    return JSON.to_native(JSON.parse_string(string), allow_objects)