Index · Object → RefCounted → Resource → JSON

JSON

Helper class for creating and parsing JSON data.

Class Description

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 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.

Properties

var data: Variant = null

Contains the parsed JSON data in Variant form.

Inherited from Resource (4)

Methods

func from_native(variant: Variant, full_objects: bool = false) -> Variant

Converts a native engine type to a JSON-compliant value.

By default, objects are ignored for security reasons, unless full_objects is true.

You can convert a native value to a JSON string like this:

func encode_data(value, full_objects = false):
	return JSON.stringify(JSON.from_native(value, full_objects))
func get_error_line() -> int

Returns 0 if the last call to parse() was successful, or the line number where the parse failed.

func get_error_message() -> String

Returns an empty string if the last call to parse() was successful, or the error message if it failed.

func get_parsed_text() -> String

Return the text parsed by parse() (requires passing keep_text to parse()).

func parse(json_text: String, keep_text: bool = false) -> Error

Attempts to parse the json_text provided.

Returns an Error. If the parse was successful, it returns OK and the result can be retrieved using data. If unsuccessful, use get_error_line() and get_error_message() to identify the source of the failure.

Non-static variant of parse_string(), if you want custom error handling.

The optional keep_text argument instructs the parser to keep a copy of the original text. This text can be obtained later by using the get_parsed_text() function and is used when saving the resource (instead of generating new text from data).

func parse_string(json_string: String) -> Variant

Attempts to parse the json_string provided and returns the parsed data. Returns null if parse failed.

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

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 INF will be replaced with 1e99999, and negative INF will be replaced with -1e99999, but they will be interpreted correctly as infinity by most JSON parsers. 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"
......}
...]
}
func to_native(json: Variant, allow_objects: bool = false) -> Variant

Converts a JSON-compliant value that was created with from_native() back to native engine types.

By default, objects are ignored for security reasons, unless allow_objects is true.

You can convert a JSON string back to a native value like this:

func decode_data(string, allow_objects = false):
	return JSON.to_native(JSON.parse_string(string), allow_objects)
Inherited from Resource (18)
func _get_rid() -> RID
func _reset_state() -> void
func _set_path_cache(path: String) -> void
func _setup_local_to_scene() -> void
func copy_from_resource(resource: Resource) -> Error
func duplicate(deep: bool = false) -> Resource
func duplicate_deep(deep_subresources_mode: Resource.DeepDuplicateMode = 1) -> Resource
func emit_changed() -> void
func get_rid() -> RID
func is_built_in() -> bool
func reset_state() -> void
func set_id_for_path(path: String, id: String) -> void
func set_path_cache(path: String) -> void
func setup_local_to_scene() -> void
func take_over_path(path: String) -> void
Inherited from RefCounted (4)
func init_ref() -> bool
func reference() -> bool
func unreference() -> bool
Inherited from Object (62)
func _get(property: StringName) -> Variant
func _get_property_list() -> Dictionary[]
func _init() -> void
func _iter_get(iter: Variant) -> Variant
func _iter_init(iter: Array) -> bool
func _iter_next(iter: Array) -> bool
func _notification(what: int) -> void
func _set(property: StringName, value: Variant) -> bool
func _to_string() -> String
func _validate_property(property: Dictionary) -> void
func add_user_signal(signal: String, arguments: Array = []) -> void
func call(method: StringName) -> Variant
func callv(method: StringName, arg_array: Array) -> Variant
func cancel_free() -> void
func connect(signal: StringName, callable: Callable, flags: int = 0) -> Error
func disconnect(signal: StringName, callable: Callable) -> void
func emit_signal(signal: StringName) -> Error
func free() -> void
func get(property: StringName) -> Variant
func get_class() -> String
func get_incoming_connections() -> Dictionary[]
func get_indexed(property_path: NodePath) -> Variant
func get_meta(name: StringName, default: Variant = null) -> Variant
func get_meta_list() -> StringName[]
func get_method_list() -> Dictionary[]
func get_property_list() -> Dictionary[]
func get_signal_connection_list(signal: StringName) -> Dictionary[]
func get_signal_list() -> Dictionary[]
func has_meta(name: StringName) -> bool
func has_method(method: StringName) -> bool
func has_signal(signal: StringName) -> bool
func is_class(class: StringName) -> bool
func is_connected(signal: StringName, callable: Callable) -> bool
func notification(what: int, reversed: bool = false) -> void
func remove_meta(name: StringName) -> void
func remove_user_signal(signal: StringName) -> void
func set(property: StringName, value: Variant) -> void
func set_block_signals(enable: bool) -> void
func set_deferred(property: StringName, value: Variant) -> void
func set_indexed(property_path: NodePath, value: Variant) -> void
func set_message_translation(enable: bool) -> void
func set_meta(name: StringName, value: Variant) -> void
func set_script(script: Variant) -> void
func set_translation_domain(domain: StringName) -> void
func to_string() -> String
func tr(message: StringName, context: StringName = &"") -> String
func tr_n(message: StringName, plural_message: StringName, n: int, context: StringName = &"") -> String

Signals

Inherited from Resource (2)
signal changed()
Inherited from Object (2)