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
繼承: Resource < RefCounted < Object
用於建立和解析 JSON 資料的輔助類。
說明
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
\nand\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.
屬性
|
方法
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 |
屬性說明
包含解析到的 JSON 資料,型別為 Variant。
方法說明
Variant from_native(variant: Variant, full_objects: bool = false) static 🔗
將引擎原生型別轉換為 JSON 相容型別。
出於安全原因,預設會忽略物件,除非 full_objects 為 true。
將原生值轉換為 JSON 字串的方法如下:
func encode_data(value, full_objects = false):
return JSON.stringify(JSON.from_native(value, full_objects))
如果上一次呼叫 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.
If sort_keys is true, the keys of any Dictionarys are sorted alphabetically when converting to JSON. If full_precision is true, when stringifying floats, the unreliable digits are stringified in addition to the reliable digits to guarantee exact decoding.
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.
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. If set to an empty string, the JSON will be on a single line with no spacing, which allows for smaller file sizes.
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, "", false)
{"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", false)
{
"name": "my_dictionary",
"version": "1.0.0",
"entities": [
{
"name": "entity_0",
"value": "value_0"
},
{
"name": "entity_1",
"value": "value_1"
}
]
}
## JSON.stringify(my_dictionary, "...", false)
{
..."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_objects 為 true。
將 JSON 字串轉換回原生值的方法如下:
func decode_data(string, allow_objects = false):
return JSON.to_native(JSON.parse_string(string), allow_objects)