Attention: Here be dragons
This is thelatest (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
Inherits:Resource<RefCounted<Object
Helper class for creating and parsing JSON data.
Description
TheJSON 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 aVariant that can be used within Godot. If successfully parsed, usedata to retrieve theVariant, and use@GlobalScope.typeof() to check if the Variant's type is what you expect. JSON Objects are converted into aDictionary, but JSON data can be used to storeArrays, numbers,Strings and even just a boolean.
vardata_to_send=["a","b","c"]varjson_string=JSON.stringify(data_to_send)# Save data# ...# Retrieve datavarjson=JSON.new()varerror=json.parse(json_string)iferror==OK:vardata_received=json.dataiftypeof(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 staticparse_string() method, but it doesn't handle errors.
vardata=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
\nand\t.Numbers are parsed usingString.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.
Properties
|
Methods
from_native(variant:Variant, full_objects:bool = false)static | |
parse_string(json_string:String)static | |
stringify(data:Variant, indent:String = "", sort_keys:bool = true, full_precision:bool = false)static | |
Property Descriptions
Variantget_data()
Contains the parsed JSON data inVariant form.
Method Descriptions
Variantfrom_native(variant:Variant, full_objects:bool = false)static🔗
Converts a native engine type to a JSON-compliant value.
By default, objects are ignored for security reasons, unlessfull_objects istrue.
You can convert a native value to a JSON string like this:
funcencode_data(value,full_objects=false):returnJSON.stringify(JSON.from_native(value,full_objects))
Returns0 if the last call toparse() was successful, or the line number where the parse failed.
Stringget_error_message()const🔗
Returns an empty string if the last call toparse() was successful, or the error message if it failed.
Return the text parsed byparse() (requires passingkeep_text toparse()).
Errorparse(json_text:String, keep_text:bool = false)🔗
Attempts to parse thejson_text provided.
Returns anError. If the parse was successful, it returns@GlobalScope.OK and the result can be retrieved usingdata. If unsuccessful, useget_error_line() andget_error_message() to identify the source of the failure.
Non-static variant ofparse_string(), if you want custom error handling.
The optionalkeep_text argument instructs the parser to keep a copy of the original text. This text can be obtained later by using theget_parsed_text() function and is used when saving the resource (instead of generating new text fromdata).
Variantparse_string(json_string:String)static🔗
Attempts to parse thejson_string provided and returns the parsed data. Returnsnull if parse failed.
Stringstringify(data:Variant, indent:String = "", sort_keys:bool = true, full_precision:bool = false)static🔗
Converts aVariant 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 anumber type. Therefore, converting a Variant to JSON text will convert all numerical values tofloat types.
Note: Iffull_precision istrue, when stringifying floats, the unreliable digits are stringified in addition to the reliable digits to guarantee exact decoding.
Theindent 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 with1e99999, 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 withnull, and it will not be interpreted as NaN in JSON parsers. If you expect non-finite numbers, consider passing your data throughfrom_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"......}...]}
Variantto_native(json:Variant, allow_objects:bool = false)static🔗
Converts a JSON-compliant value that was created withfrom_native() back to native engine types.
By default, objects are ignored for security reasons, unlessallow_objects istrue.
You can convert a JSON string back to a native value like this:
funcdecode_data(string,allow_objects=false):returnJSON.to_native(JSON.parse_string(string),allow_objects)