?How to save a dictionary to an existing file to modify the .json files contents

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

I have this code:

	if !FileAccess.file_exists(Global.path["config"]):
	#copy the default config to the user directory
	DirAccess.copy_absolute("res://defaultconfig.cfg", Global.path["config"])
	var config = ConfigFile.new()

	#update the config file
	config.set_value("Flaunch", "Flaunch", false)
	#update the stage file
	#open the file
	var file = FileAccess.open(Global.path["stagefile"], FileAccess.READ)
	#save it's contents to a dictionary
	var json_dict = JSON.parse_string(file.get_as_text())
	#close the file

but I can’t seem to figure out how to save the file once I’ve added something to the dictionary

:bust_in_silhouette: Reply From: jgodfrey

Something like this should get you started:

func _ready():
	var name = "C:/myfile.json"
	var d = {"score": 100, "level": 6, "state": "refueling"}
	var s = JSON.stringify(d, "\t")
	var f = FileAccess.open(name, FileAccess.WRITE)
	if f:
		print("file open failed")

In the above d is the dictionary you’re trying to save. That’s converted to a JSON string via the JSON.stringify() call. Once you have a string, you can save is using usual methods (f.store(line) above.

actually I’m working with json files from an api and I just wanted to add something to it my mistake was in not opening the file in read write mode and not giving the http request enough time to completely download the file
here is my code for example to anyone who wants to just add data to a json file:

if FileAccess.file_exists(Global.path["stagefile"]):
	print("being modified")
	#open the file
	var file = FileAccess.open(Global.path["stagefile"], FileAccess.READ_WRITE)
	#put file contents in a dictionary
	var json_text = FileAccess.get_file_as_string(Global.path["stagefile"])
	var json_dict = JSON.parse_string(json_text)
	#add the createtime value in the dictionary
	json_dict["createtime"] = Time.get_unix_time_from_system()
	#save store the dictionary in the file
	#close the file at user://stage.json
	print("done modifying: user://stage.json")
elif !FileAccess.file_exists(Global.path["stagefile"]):
	print("file: user://stage.json does not exist")
else: print("unknown error in modify() from MainScript.gd")

Where I reference Global.path[“stagefile”] I’m just refencing a variable dictionary called in a script called Global wich I set to autostart so that I can store some information in there wich I will be using throughout the entire program. so Global.path[“stagefile”] is exactly the same as user://stage.json

Cyber-Kun | 2023-03-11 08:47