• 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!

Efficient Way to Read Multiple JSON Files

C

ChaosX2

Guest
Hey Everyone,

I by no means am having trouble grabbing data from some JSON files in my project, but I'm wondering if anyone can enlighten me in a more efficient way to read multiple JSON files. Because I'm running the same lines of code for each file, I can't help but wonder if there's a better way to go about it. Here's some of my code below.

Code:
var jsonFile_charDB = file_text_open_read("characterDatabase.json"); //opens JSON file
var jsonFile_itemDB = file_text_open_read("itemDatabase.json");

//Character Database
if(jsonFile_charDB != -1) //If it exist
{
    while(!file_text_eof(jsonFile_charDB)) //not at end of file
        fileData_charDB += file_text_readln(jsonFile_charDB); //read file
}
file_text_close(jsonFile_charDB); //close when done

//Item Database
if(jsonFile_itemDB != -1) //If it exist
{
    while(!file_text_eof(jsonFile_itemDB)) //not at end of file
        fileData_itemDB += file_text_readln(jsonFile_itemDB); //read file
}
file_text_close(jsonFile_itemDB); //close when done

//Decode data: return ds_map
var jsonMap_charDB = json_decode(fileData_charDB);
var jsonMap_itemDB = json_decode(fileData_itemDB);

//Find list values in map
var mapList_charDB = ds_map_find_value(jsonMap_charDB, "default");
var mapList_itemDB = ds_map_find_value(jsonMap_itemDB, "default");

//Total rows in each respective list
var totalChars = ds_list_size(mapList_charDB);
var totalItems = ds_list_size(mapList_itemDB);
Just some of the code, but as you can see, I repeat the same lines of code for each file. Perhaps, I'm overthinking, but thought to ask just in case.
 

YellowAfterlife

ᴏɴʟɪɴᴇ ᴍᴜʟᴛɪᴘʟᴀʏᴇʀ
Forum Staff
Moderator
You could make a script like
Code:
/// ds_list_load_from_json_file(path)
var file = file_text_open_read(argument0);
if (file < 0) return -1;
//
var data = "";
while (!file_text_eof(file)) data += file_text_readln(file);
file_text_close(file);
//
var map = json_decode(data);
if (map < 0) return -1;
//
var list = map[?"default"];
if (list == undefined) return -1;
//
return list;
and then do
Code:
var mapList_charDB = ds_list_load_from_json_file("characterDatabase.json");
 
Top