Introduction to JSON in SplashKit
JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write, and for machines to parse and generate.
Written by: Jonathan Tynan and others
Last updated: October 2024
What is JSON?
JSON is often used in various programming environments, including game development, for data storage and configuration. In SplashKit, JSON functionality allows developers to efficiently manage game settings, level data, and more. This section of the tutorial introduces JSON, its basic structure, and provides an overview of its application in SplashKit.
Basic Structure of a JSON File
A basic JSON file might look like this:
JSON objects are made up of values associated with keys. In this example, gameTitle
is the key associated with the string "My New Game"
, screenSize
is the key for an object with two numeric values (width and height), and an array of strings is assigned as the value for the key levels
.
Overview of JSON in SplashKit
SplashKit simplifies the process of working with JSON files in your games. It provides functions for reading JSON files, allowing us to easily retrieve values and load configurations or game data. Additionally, it offers functions for writing JSON files, enabling us to save configurations and game data.
Getting Started with JSON in SplashKit
To begin using JSON in SplashKit, we must have our files in the correct locations. Run the following command in your project directory to generate the resources folder.
This command creates sub-folders for each type of resource. One of these is named json
and that is where we place our JSON files. To begin lets take the example JSON file above and place it into the json
folder with the name game_data.json
. To access the values in this file we can now do the following:
In this code example, we first use Json From File to load a JSON object containing details from the game_data.json
file.
Next, we retrieve the value associated with the gameTitle
key using Json Read Stringand output it to the console. Finally, we free the JSON object using Free Json before exiting the program. This deallocates any memory that was allocated to the JSON object, helping to prevent memory-related errors such as Segmentation Fault
. We can build this program using the following command.
And run it with:
When we run this program, it should display the following output in the console:
Checking Keys
But what if we didn’t have a gameTitle
key in our JSON? Well, error messages will be produced indicating that this key is null
. To prevent this, we can use the Json Has Key function to check if the key is present and then do actions based on whether it has been found or not. We could then turn the previous example into the following code:
We have successfully loaded our JSON file and retrieved the value associated with the gameTitle
key. In the next tutorial, we’ll delve deeper into retrieving other values stored within a JSON object.