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.
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.
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:
Running this prints the following to the terminal:
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:
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.