Array item changes type after loading

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

After saving and loading type changes TYPE_INT to TYPE_REAL.
Because of this a many of errors, for example match does not work correctly.

I write an example code below:

var array = ["items", 0]
   
func test():
	
	print("TYPE BEFORE: ", typeof(array[1]))
	_save()
	_load()
	print("TYPE AFTER: ", typeof(array[1]))
	
	pass

func _save():
	
	var data = {
		example = {
			array = array
		}
	}
	
	var save_file = File.new()
	save_file.open("res://test.json", File.WRITE)
	save_file.store_line(to_json(data))
	save_file.close()
	
	pass

func _load():
	
	var save_file = File.new()
	if(not save_file.file_exists("res://test.json")): return
	save_file.open("res://test.json", File.READ)
	var data = {}
	data = parse_json(save_file.get_as_text())
	array = data['example']['array']
	save_file.close()
	
	pass

How set default array item type? And how to fix it? Thanks!
Something helps int(array[1]), but I would like a more comprehensive solution.

:bust_in_silhouette: Reply From: estebanmolca

It seems that json converts integers to float. You can convert any float in godot to integer with: int (my_float_var)

I know about that. Are there any other options how to get around this?
for example, to set the type during loading

WellStacked | 2020-06-14 09:31

In general, I solved the problem. I assign types at loading

WellStacked | 2020-06-14 11:27

Once you load the data (after parse_json ()), you can loop through it, and if it finds a value with real type replace the same value with a type int in the already loaded data. I don’t know if it is a very elegant solution but it could work. One problem is that if you want to save floats together with int everything will be converted to int. A solution to the latter could be to also save a string explicitly specifying the type along with the data.

func _load():

	var save_file = File.new()
	if(not save_file.file_exists("res://test.json")): return
	save_file.open("res://test.json", File.READ)
	var data = {}
	data = parse_json(save_file.get_as_text())
	array = data['example']['array']
	save_file.close()
	
	for i in array.size():
		if typeof(array[i]) == TYPE_REAL:
			array[i] = int(array[i])
					

	pass

estebanmolca | 2020-06-14 13:44

ok, I leave an example below, I had prepared it but it was without internet.

estebanmolca | 2020-06-14 13:46

I did about the same, thanks anyway)

WellStacked | 2020-06-14 17:16