Help. I want to read some variables from the game and create a JSON with that data.

Hi all,

My objective is to do like a test leaderboard of sorts. So what I want to do is read some ingame variables and store them in a JSON file.
I have basic javascript knowledge.

Could you guide me as into how to create this json file so I can use that data elsewhere?

Thank you!
You'll want to use the file system, and stringify the object with JSON.stringify

let fs = require('fs');
// Now the temporary variable fs has access to read/write to the machine's file system

let dat = JSON.stringify(obj)
// obj is the object you plan on storing as JSON

fs.writeFile(stringFilePath, dat)
//first arg is the string that holds your filepath, and the name of the file you wish to write to or create

And that's pretty much it.
Your file path would look something like
'data/Cardbook.json' if, for example, you wanted to create or overwrite a json file called 'Cardbook'

EDIT: fyi, in case you didn't know how to load them, there are two ways I can show you to approach this.

First method is to add this file to the DatabaseManager._databaseFiles array, preferably by aliasing the DatabaseManager.loadDatabase function.
This method will ensure that your JSON files will load and create objects for themselves when the game is loaded. This is probably the better method because you can write ensure that whenever any other object like $gamePlayer would be available, the object you use to read your JSON will be available. This will result in a global variable, just like $gamePlayer that is always available once the game loads.

let alias_loadDatabase = DatabaseManager.loadDatabase;

DatabaseManager.loadDatabase = function(){
DatabaseManager._databaseFiles.push({name:$myCustomData, src:'Cardbook.json'});
alias_loadDatabase.call(this);
}



The second method is to use the file system, like when you write to a JSON file. However, you'll need to parse the data for it to become an object again. Otherwise, it will just be an array of numbers. This is better if you only the data temporarily, especially if you have a lot.

let myData = JSON.parse(fs.readFileSync('data/Cardbook.json'))
I think it is not that complicated then..I´ll give it a try and if I have more question, i´ll be back.

thank youuuu!
@standardplayer Yeap, worked perfectly. Thanks!
A note, just in case...I don't think this will work for non-local (i.e. Web-based) deployments, since in that situation there is no access to the filesystem, i.e. the library request require('fs') will fail.

If you need it to work with web-based stuff (like the game saves), check out the getItem and setItem methods of localStorage. Also, Utils.isNwjs() should return true iff the game is running in local mode. 🙂
Im not planning to do web deployments, but if I ever need it, thank you for the heads up =)

Original thread: https://forums.rpgmakerweb.com/threads/help-i-want-to-read-some-variables-from-the-game-and-create-a-json-with-that-data.118024/