概述
在Godot 4.3中读取JSON配置文件,可以通过以下步骤实现:
步骤说明
-
读取文件内容 :使用
FileAccess
类打开并读取JSON文件。 -
解析JSON数据 :使用
JSON
类解析读取到的文本内容。 -
错误处理:处理文件不存在或JSON格式错误的情况。
编码
python
extends Node
func _ready():
var config_data = load_config()
if config_data:
print("配置加载成功:", config_data)
else:
print("配置加载失败")
func load_config():
# 打开文件
var file = FileAccess.open("res://config.json", FileAccess.READ)
if not file:
push_error("无法打开配置文件!")
return null
# 读取文本内容
var content = file.get_as_text()
file.close() # 显式关闭文件
# 解析JSON
var json = JSON.new()
var parse_error = json.parse(content)
if parse_error != OK:
push_error("JSON解析错误:%s(第%d行)" % [
json.get_error_message(),
json.get_error_line()
])
return null
# 返回解析后的数据(字典或数组)
return json.data
-
文件路径:
-
res://
:项目资源目录,适用于只读配置文件。 -
user://
:用户数据目录,适用于可写入的配置。
-
-
错误处理:
-
使用
FileAccess.open()
时检查返回值,确保文件存在。 -
解析JSON时检查
parse()
的返回值,捕获语法错误。
-
-
数据结构:
-
JSON对象会被转换为GDScript的
Dictionary
。 -
JSON数组会被转换为
Array
。
-