Skip to content

Reading JSON Data in SplashKit

After understanding the basics of JSON in SplashKit, this part of the tutorial focuses on how to read and parse JSON data. Reading JSON data is essential for game development tasks such as loading game settings, level configurations, or player data.
Written by: Jonathan Tynan and others
Last updated: October 2024


Reading JSON Objects

In the previous tutorial we loaded the following JSON file and read the game title from it. Lets extend this a little, and dive a further into extracting values from this structure.

{
"gameTitle": "My New Game",
"fullScreenMode": false,
"numPlayers": 1,
"screenSize": {
"width": 800,
"height": 600
},
"levels": ["level1", "level2", "level3"]
}

Accessing Values

To access values in JSON objects like strings, numbers, or booleans, you can use functions like Json Read String, Json Read Number As Int, or Json Read Bool. We use these functions like the following code snippet.

string title = json_read_string(game_data, "gameTitle");
int numPlayers = json_read_number_as_int(game_data, "numPlayers");
bool isFullScreen = json_read_bool(game_data, "fullScreenMode");

Working with JSON Arrays

If the data is an array, like the value stored for the levels key, we can obtain the data through Json Read Array and store it into a dynamic string array variable (such as vector<string> in C++, or List<string> in C#). Then we can loop through the entries in the array, and do some actions with the stored data.

Below is an example of this:

vector<string> levels;
json_read_array(game_data, "levels", levels);
int num_levels = levels.size();
for(int i = 0; i < num_levels; i++)
{
write("Got level: ");
write_line(levels[i]);
}

Running this prints the following to the terminal:

Got level: level1
Got level: level2
Got level: level3

Extracting Nested JSON Objects

SplashKit’s JSON functionality allows you to extract various types of data, including basic types mentioned previously, but also even nested JSON objects. In our example file the value for the screenSize key is a JSON object. The following code demonstrates how to extract this object:

json game_screen_size = json_read_object(game_data, "screenSize");
int width = json_read_number_as_int(game_screen_size, "width");
int height = json_read_number_as_int(game_screen_size, "height");

In this example, Json Read Object is used to extract the nested JSON object, and then the values are read from this nested object. These variables can then be used to define the window size for this game.

Conclusion

Reading JSON data with SplashKit is a straightforward process that can greatly enhance the flexibility and functionality of your game. It enables dynamic loading of game content and configurations, making your game more adaptable and easier to manage.

In the next part of this tutorial, we explore how to write and modify JSON data, allowing you to save game states, configurations, and player preferences.