Append data in JSON file

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

Hi guys

I am creating a function which gets the coordinates of puzzle pieces and store them in a json file. The problem is, its only saving one entry and is not appending the entries into file.
Related code is below :

if event is InputEventMouseButton and !event.pressed:
var event_pos = get_position()
var p_id = id
write_to_file(event_pos, id)

func write_to_file(pos, p_id):
print(pos, p_id)

var event_data = {}
var data_files = File.new()
if data_files.open(global.Event_FILE_PATH, File.WRITE) != OK:
	return
event_data["Position"] = pos
event_data["Piece_ID"] = p_id

data_files.store_line(to_json(event_data))
data_files.close()

I’m pretty new to Godot/json, but afaik If event_data[“Position”] and event_data[“Place_ID”] are lists:

event_data["Position"].append(pos)
event_data["Piece_ID"].append(p_id)

FT_Anx | 2019-11-18 19:58

Putting Position and ID into arrays, anyhow its solved and thanks alot for your answer.

hsn | 2019-11-20 17:57

:bust_in_silhouette: Reply From: hsn

I have solved the problem as follows and its working fine now , however if needed I can share the full code for Write_to_file function

if data_file.file_exists(global.Event_FILE_PATH): data_file.open(global.Event_FILE_PATH, File.READ_WRITE)
else: data_file.open(global.Event_FILE_PATH, File.WRITE)