Dictionary to Json

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

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

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

{“Challenge”:“text with spaces”, “Controls”:“1”, “Graphics”:“1”}

:bust_in_silhouette: Reply From: p7f

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


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

JSON.print( myDictionaryVar ) was the solution.

DavidPeterWorks | 2019-01-07 11:27

You are welcome!

p7f | 2019-01-07 12:17

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

mustapha | 2019-04-03 14:02

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

i get the type “18” what is this?

lxknvlk | 2020-03-17 20:13

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

@GlobalScope — Godot Engine (3.4) documentation in English

Good luck!

stormwarestudios | 2021-09-16 04:48