+3 votes

I would like to convert my dictionary variable to json string.
What is the best way to do that with standard functions?

From
{Challenge: text with spaces, Controls:1, Graphics:1}

To
{"Challenge":"text with spaces", "Controls":"1", "Graphics":"1"}

in Engine by (325 points)

1 Answer

+11 votes
Best answer

You can use the JSON helper class... if your dictionary is:

var dict = {"Challenge": "text with spaces", "Controls": 1, "Graphics": 1}

(note that your dictionary MUST have quotes arround keys)

you can get a JSON string with:

var jstr = JSON.print(dict)

And you can parse it to a JSONParseResult with:

var res = JSON.parse(jstr)

The JSON parse result has some variables you can se here. There you can get the JSON object with:

var obj = res.result

You can check if the object returned is a dictionary or an array with

typeof(obj)

If you only need to convert dict to JSON string, then the JSON.print is what you are looking for.

by (3,503 points)
selected by

JSON.print( myDictionaryVar ) was the solution.
Thanks.

You are welcome!

I have try JSON.print without quotes in my dict and it also worked (in godot 3.1)

when i do

func map_server_user_response(body: PoolByteArray) -> User:
  var stringResult: String = body.get_string_from_utf8()
  var jsonParseResult: JSONParseResult = JSON.parse(stringResult)
  var userJson = jsonParseResult.result
  print(typeof(userJson))

i get the type "18" what is this?

Bit late to the party, but types are defined here under entries prefixed with TYPE_:

https://docs.godotengine.org/en/3.4/classes/class_%40globalscope.html

Good luck!

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.