• Hey Guest! Ever feel like entering a Game Jam, but the time limit is always too much pressure? We get it... You lead a hectic life and dedicating 3 whole days to make a game just doesn't work for you! So, why not enter the GMC SLOW JAM? Take your time! Kick back and make your game over 4 months! Interested? Then just click here!

SOLVED Trouble with importing text from JSON file (returns "undefined")

K

Kugua

Guest
Hello!

I'm new to gamemaker and still learning the ropes. I've been playing around with managing large amounts of text by saving the text in a csv file, converting to JSON, and then loading the JSON file in the game. Using v2.2.5.378.

The problem I'm running into is that when I load the text, I get "undefined" every time I try to draw strings from it.

To test this, I'm using a super simple JSON file named "text.json" that is just this:

Code:
[
{
   "ONE": "Hello.",
   "TWO": "Hey! How are you doing today?"
}
]
I then print the text in a draw event like this:

Code:
text_file = json_decode("text.json");
var _print = text_file[? "TWO"];
draw_text(0, 0, _print);
I have no issues drawing text from a csv file using similar logic. I've been Googling nonstop, referring to the documentation, and trying various other methods but am still getting "undefined" when I try to draw the string in the JSON file.
I feel like I'm missing something obvious. Can anyone help? It would be greatly appreciated!
 

TsukaYuriko

☄️
Forum Staff
Moderator
From the manual entry of json_decode:
NOTE: When decoding arrays, there is a map with the key "default" ONLY when an array is the top level structure, and ONLY for that top-level array. Internal lists decode directly to ds_lists without being enclosed in a ds_map.
From what I can tell, your JSON file has an array as the top-level structure, so you'd first have to get the value of the key "default" which holds the array, then the 0th element of it, THEN you can get the value of "TWO".
 
K

Kugua

Guest
THANK YOU BOTH SO MUCH! It worked!

For anyone else looking at this thread in the future, here's the code I used:

In some sort of initialization event:
Code:
text_data = "";

var file = file_text_open_read("text.json");
while (!file_text_eof(file))
{
    text_data += file_text_read_string(file);
    file_text_readln(file);
}

file_text_close(file);
In the draw event:
Code:
    var _temp_map = json_decode(text_data);
        var _default_value = ds_map_find_value(_temp_map, "default");
        var _list = ds_list_find_value(_default_value, 0);
        var _print = _list[? "TWO"];
        draw_text(0, 0, _print);
 
Top