Json returns an empty dictionary when using stringify

Godot Version

4.5

Question

I'm trying to load a list of enemies into a dictionary and spawn enemies in the level based on that dictionary, but the dictionary always returns null. This is what my json looks like (NOTE: "level" doesn't refer to different scenes, just different elevations):

{"hazards" :[
	{"level":1,"loc":250,"speed":0},
	{"level":1,"loc":500,"speed":0},
	{"level":2,"loc":800,"speed":0},
	{"level":2,"loc":400,"speed":0},
	{"level":3,"loc":0,"speed":100},
	{"level":4,"loc":1000,"speed":-30},
	{"level":5,"loc":600,"speed":0},
	{"level":5,"loc":-100,"speed":50},
	{"level":5,"loc":-300,"speed":100},
]}

and this is the part of my script that’s supposed to load the enemies:

var hazard = "res://scenes/hazard.tscn"
var level_rsrc = "res://level_jsons/test.json"
var hazard_dict : Dictionary
var a
signal start_hazards

func _ready() -> void:
	var j = load(level_rsrc)
	j.stringify(hazard_dict)
	print(hazard_dict)
	for h in hazard_dict["hazards"]:
		a = load(hazard).instantiate()
		a.position.x = h.loc
		a.position.y = $Player.position.y + (Globals.step * h.level)
		a.speed = h.speed
		a.connect(start_hazards,a.on_start)
		add_child(a)
		print("loaded hazard at level" + h.level)

You misused the JSON class a little bit. This is the correct syntax that will work in your usecase:

var hazard = "res://scenes/hazard.tscn"
var level_rsrc = "res://level_jsons/test.json"
var hazard_dict : Dictionary
var a
signal start_hazards

func _ready() -> void:
	var j = load(level_rsrc)
	hazard_dict = j.data # < this is the line I changed
	print(hazard_dict)
	for h in hazard_dict["hazards"]:
		a = load(hazard).instantiate()
		a.position.x = h.loc
		a.position.y = $Player.position.y + (Globals.step * h.level)
		a.speed = h.speed
		a.connect(start_hazards,a.on_start)
		add_child(a)
		print("loaded hazard at level" + h.level)
2 Likes