Godot 4.0 : How to get a Dictionary from a JSON type

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

I am using the get_data() method of a JSON instance.
This method returns a String data type.
I just want to convert this String to a Dictionary.

Any idea ?


Landroval | 2023-02-12 16:25

:bust_in_silhouette: Reply From: Lola

use JSON.parse() for this (there is an example usage in the integrated docs :slight_smile: ).

Thanks for the answer.

My problem is relative to Godot v4.0 (the code works in v3.3.4).

In v4.0, I have to use “js.get_data()” after the “js.parse(js_data)” call.
The “get_data()” method returns a String and I don’t see how to convert this String in a Dictionary type ?

Chlipouni | 2021-10-14 05:25

My answer was relative to godot 4. Here is a code snippet that works on my end:

func read_json():
    var f = File.new()
    var open_err = f.open("res://example.json", File.READ)
    var json_object = JSON.new()
    var parse_err = json_object.parse(f.get_as_text())
    return json_object.get_data()

Where example.json is copied from here (the first dictionary).

What string does your get_data call return?
Check what error you get when parsing the content, maybe your file isn’t valid as a dictionnary and therefor interpreted as a string?

Lola | 2021-10-14 14:10

Lola, thanks a lot for your help !
I was using “js.stringify” before calling “js.parse”.
Now the code works.

Chlipouni | 2021-10-15 10:25

:bust_in_silhouette: Reply From: cn80

According to the docs you can use parse_json

If it’s already in a JSONParseResult instance, you should be able to do the following:

var p = JSON.parse('["hello", "world", "!"]')
:bust_in_silhouette: Reply From: Losatu

Works for me with Godot 4 Alpha 7:

var my_json = JSON.new()
var parse_result = my_json.parse(json_text)

if parse_result != OK:
	print("Error %s reading json file." % parse_result)

var data = my_json.get_data()