How do I read a json file

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

I have a json file which looks like this:

{
    "word_1" : {
         "en" : "engine"
         "de" : "motor"
     }
    "word_2" : {
         "en" : "cookie"
         "de" : "keks"
     }
}

In my script I have

var words = {
    "word_1_en" : "",
    "word_1_de" : "",
    "word_2_en" : "",
    "word_2_de" : ""
}

Now how do I get the word_1_en set from the json file {"word_1":{"en":""}}
And the same of course for the other values.

:bust_in_silhouette: Reply From: Lola

Hello,
to turn the content of a JSON file into a godot variable you can use the global parse_json function:

func read_json_file(file_path):
    var file = File.new()
    file.open(file_path, File.READ)
    var content_as_text = file.get_as_text()
    var content_as_dictionary = parse_json(content_as_text)
    return content_as_dictionary

For your problem I would use the same data structure in the JSON file and in the dictionnary, that is to say formatting the JSON file this way so that there is no conversion needed:

{
    "word_1_en" : ""
    "word_1_de" : ""
    "word_2_en" : ""
    "word_2_de" : ""
}

Finally, it looks like your a trying to use a custom solution to handle translations.
In case you didn’t know, godot has tools to support that, see the relevant docs.

Here’s the updated code for Godot 4.x, as File has been renamed, and parse_json does not exist (anymore)

func parse_json(text):
  return JSON.parse_string(text)

func read_json_file(file_path):
	var file = FileAccess.open(file_path, FileAccess.READ)
	var content_as_text = file.get_as_text()
	var content_as_dictionary = parse_json(content_as_text)
	return content_as_dictionary

s4300 | 2023-06-03 15:09