Saving multiple characters to json

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Nikola-Milovic

So I have a RPG game with multiple characters. I want to store which character player has unlocked and their stats, level, skills they’ve learned and so on. For now I got the save system working. Just have no idea how to store these in the same file. As okay, character has 5 characters for example. I saved them with store line and now each one has its own line. Now the problem arises if I want to save the data of the 3rd character for example. I don’t know which line the character belongs ( character 3 doesnt neceserally mean third line, i just say it for the sake of simplicity). So my question is how to approach this. I might switch to resources if thats more optimized and simpler to work with.

Additional question, can i create a new folder for his to keep the data organized(on mobile), i havent found much info on saving on mobile.

sorry for 2 questions they seem related enought

Much love, thank you <3

:bust_in_silhouette: Reply From: supper_raptor

use these function to save data

func save_data(save_path : String, data) -> void:
	var data_string = JSON.print(data)
	var file =
	var json_error = validate_json(data_string)
	if json_error:
		print_debug("JSON IS NOT VALID FOR: " + data_string)
		print_debug("error: " + json_error)
		return, file.WRITE)

func load_data(save_path : String):
	var file : File =
	if not file.file_exists(save_path):
		print_debug('file [%s] does not exist; creating' % save_path)
		save_data(save_path, {}), file.READ)
	var json : String = file.get_as_text()
	var data = parse_json(json)
	return data

You have 5 character so you can structure their data by creating dictionary

#individual character data
var char_data1 = {
	hp = 100,
	kills = 100,
	xp = 20

#data of 5 character
var character_data = {
	char1 = char_data1,
	char2 = char_data2,
	char3 = char_data3,
	char4 = char_data4,
	char5 = char_data5,

#then call save func
save_data("user://character.dat", character_data)