JSON

继承: Resource < RefCounted < Object

用于创建和解析 JSON 数据的辅助类。

描述

JSON 类允许所有数据类型与 JSON 字符串相互转换。可用于将数据序列化,例如保存到文件或通过网络发送。

stringify() 用于将任何数据类型转换为 JSON 字符串。

parse() 用于将任何现有的 JSON 数据转换为可以在 Godot 中使用的 Variant。如果解析成功,使用 data 检索 Variant,并使用 @GlobalScope.typeof() 检查 Variant 的类型是否符合你的预期。JSON 对象被转换为 Dictionary,但 JSON 数据可用于存储 Array、数字、String,甚至只是一个布尔值。

var data_to_send = ["a", "b", "c"]
var json_string = JSON.stringify(data_to_send)
# 保存数据
# ...
# 检索数据
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) # 输出该数组。
    else:
        print("意外数据")
else:
    print("JSON 解析错误:", json.get_error_message(), " 位于 ", json_string, " 行号 ", json.get_error_line())

你也可以使用静态的 parse_string() 方法解析字符串,但该方法不会处理错误。

var data = JSON.parse_string(json_string) # 如果解析失败则返回 null。

注意:两种解析方式都不完全符合 JSON 规范:

  • 数组或对象中的尾随逗号将被忽略,而不是引起解析器错误。

  • 换行符和制表符在字符串文字中被接受,并被视为它们相应的转义序列 \n\t

  • 使用 String.to_float() 解析数字,这通常比 JSON 规范更宽松。

  • 某些错误不会导致解析器错误,例如 Unicode 序列无效,但是该字符串会被清理并将错误记录到控制台。

属性

Variant

data

null

方法

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


属性说明

Variant data = null 🔗

包含解析到的 JSON 数据,类型为 Variant


方法说明

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

将引擎原生类型转换为 JSON 兼容类型。

出于安全原因,默认会忽略对象,除非 full_objectstrue

将原生值转换为 JSON 字符串的方法如下:

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

int get_error_line() const 🔗

如果上一次调用 parse() 成功,则返回 0,否则返回解析失败的行号。


String get_error_message() const 🔗

如果上一次调用 parse() 成功,则返回空字符串,否则返回失败时的错误消息。


String get_parsed_text() const 🔗

返回由 parse() 解析的文本(要求向 parse() 传递 keep_text)。


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

尝试解析提供的 json_text

返回 Error。如果解析成功则返回 @GlobalScope.OK,并且可以使用 data 检索该结果。如果不成功,请使用 get_error_line()get_error_message() 来识别失败的原因。

如果想要自定义错误处理,可以使用的 parse_string() 的非静态版本。

可选的 keep_text 参数会让解析器保留原始文本的副本。该文本稍后可以使用 get_parsed_text() 函数获取,并在保存资源时使用(而不是从 data 生成新文本)。


Variant parse_string(json_string: String) static 🔗

试图解析提供的 json_string,并返回解析后的数据。如果解析失败,返回 null


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 🔗

将使用 from_native() 创建的 JSON 兼容值转换回引擎原生类型。

出于安全原因,默认会忽略对象,除非 allow_objectstrue

将 JSON 字符串转换回原生值的方法如下:

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