Attention | Topic was automatically imported from the old Question2Answer platform. | |
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