Error loading Json using integers as keys

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

Hi.
I can’t load properly a dictionary from a json when it uses integers as keys. When I use the same dictionary on script (with integers as keys) it works fine.

My code with dictionary in script (it is ok):

func _ready():
	var dic = {
	0:"cat",
	1:"dog",
	2:"bird"
}
	
	for key in dic:
		print(key)
		print(dic[key])

Output:

0
cat
1
dog
2
bird

My code with dictionary in json file (it gives me error):

func _ready():
	var dic = load_json("res://Data/", "test.json")
	
	for key in dic:
		print(key)
		print(dic[key])

func load_json(pat, file):
	var path = pat + file
	var load_dict = File.new()
	if not load_dict.file_exists(path):
		print (path + " don't exist!")
		return null
	load_dict.open(path, File.READ)
	var load_dict_json = JSON.parse(load_dict.get_as_text())
	load_dict.close()
	print(load_dict_json.error_string) #output -> Expected key
	return load_dict_json.result

The json file:

{
	0:"cat",
	1:"dog",
	2:"bird"
}

Error: Unable to iterate on ogject of type ‘Nill’.

If i change the keys to strings(“0”:“cat”, “1”:“dog”, “2”:“bird”), it works fine in script and in the json file.
Am I doing something wrong? How can I use integers as keys in json file?
Thanks.

IIRC, the keys for JSON files must be strings. Therefore, on retrieval, cast the string key back to integers.

Ertain | 2021-02-02 00:38

:bust_in_silhouette: Reply From: clemens.tolboom

According to JSON a JSON object has a string as key.

So your Dictionary keys must be strings.

This was my code to test this

var d:Dictionary = {0:1,"2":3}
for k in d:
	print(typeof(k), k, typeof(d[k]), d[k])
#var json_string= '{0:1,\n"2":3}' # bad
var json_string= '{"0":1,\n"2":3}' # good
var p = JSON.parse(json_string)
if typeof(p.result) == TYPE_DICTIONARY:
	print(p.result)
else:
	push_error("JSON parse error: '%s' in line '%d'." % [p.error_string, p.error_line])