how to save dictionary into a file

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By 51m0n55

how to save this dictionary:

var save_vars = {
	"highscore":highscore,
	"games_played":games_played
}

into a file?

I couldn’t figure it out from docs or other posts…

:bust_in_silhouette: Reply From: jgodfrey

Something like this should work:

onready var persistFile = "user://savedata.txt"
onready var saveHandle = File.new()

func saveUserData(dict):
	saveHandle.open(persistFile, File.WRITE)
	saveHandle.store_line(to_json(dict))
	saveHandle.close()

Then, call saveUserData() like:

saveUserData(save_vars)

Note, the above is extracted from a working persistence script, so you may need to season it to taste.

and how do i convert the json to dict? asking because i need to load it

edit: nvm i got it thanks for helping :slight_smile:

51m0n55 | 2022-08-26 17:43

I see you got it, but in case it’s helpful, to load, use something like this:

saveHandle.open(persistFile, File.READ)
saveDict = parse_json(saveHandle.get_line())
saveHandle.close()

jgodfrey | 2022-08-26 17:48