The Godot Q&A is currently undergoing maintenance!

Your ability to ask and answer questions is temporarily disabled. You can browse existing threads in read-only mode.

We are working on bringing this community platform back to its full functionality, stay tuned for updates.

godotengine.org | Twitter

0 votes

Hi!

I have the contents of a dictionary below that I want converted into a string.

var dictionary_as_string = JSON.parse("{9:[\"Berry\", 6]}") 

if typeof(dictionary_as_string.result) == TYPE_DICTIONARY: 
    print("dictionary")
else:                  
    print("not dictionary")

print("result; ",dictionary_as_string.result)

However, dictionary_as_string.result returns null and doesn't convert into a string. It also prints "not dictionary". If I change the dictionary contents from "{9:[\"Berry\", 6]}" as used above to "{\"Berry\": 6}", it is converted into a string successfully. Why is this and how can I convert the contents to a string?

Godot version 3.2.3
in Engine by (15 points)

aren't JSONS a strings in the end ?
just str(result)
if You can print something to console, You can also stror var2str it succesfully

I've tried it, it still prints null both times. If you try to make a variable with a null value a string, it still will be null. I don't know how to solve this?

no man. It is a string, that says "null".
That clearly means, Your dictionary contains null. Result of parsing is null. JSON is invalid.

1 Answer

+1 vote
Best answer

As documented at https://www.json.org/json-en.html, the key in a JSON object must be a string.

So, when parsing that string as JSON, you can't have that integer key. If you print error_string after the call to JSON.parse (as below), you'll see a meaningful error...

(Also, note that I've cleaned up the string creation syntax a bit...)

var dictionary_as_string = JSON.parse('{9:["Berry", 6]}')
print(dictionary_as_string.error_string)

To fix it, you'll need to make that key a string, like:

var dictionary_as_string = JSON.parse('{"9":["Berry", 6]}')
if typeof(dictionary_as_string.result) == TYPE_DICTIONARY:
    print("dictionary")
else:
    print("not dictionary")

That should result in the following output:

dictionary

by (22,674 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 [email protected] with your username.