0 votes

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.

Godot version 3.2.3
in Engine by (79 points)
edited by

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

1 Answer

+1 vote
Best answer

According to https://www.json.org/json-en.html 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])
by (638 points)
selected by
Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to webmaster@godotengine.org with your username.