JSON in Godot – Complete Guide

Welcome to the World of JSON in Godot 4

If you’ve embarked on the thrilling path of game development with Godot 4, you’re about to take a deeper dive into a crucial skill that will immensely aid in the way you handle data in your games. JSON, short for JavaScript Object Notation, is a lightweight data-interchange format that Godot leverages for a variety of tasks, from saving game states to networking. It stands as a readable and efficient way to serialize and transmit data between your game and servers, or even just between different scenes. Let’s unwrap the mysteries of JSON in Godot 4 and see how it enriches your game development toolkit!

What is JSON?

JSON is a universally loved data format used across various programming languages for storing and transporting data. It’s built on two simple structures:

  • Objects: A collection of key/value pairs (akin to dictionaries in Godot)
  • Arrays: An ordered list of values (similar to lists or arrays in most languages)

What is it for in Godot 4?

In Godot 4, the JSON class serves as a helper for creating and parsing JSON data, transforming Godot’s data types into JSON strings and vice versa. This dual functionality opens the door to a realm of possibilities, from persisting player preferences and game states to complex data transmission for multiplayer gameplay.

Why should I learn it?

Understanding JSON in Godot is a small learning curve with a huge payoff. With knowledge of JSON and how to manage it in Godot, you’ll be able to:

  • Save and load game data seamlessly
  • Communicate with web servers for features like high score tables or multiplayer matchmaking
  • Design complex systems that require exchange of structured data
  • Work with modding communities by providing a familiar and accessible data format

Equipped with the power of JSON, you’ll unlock the potential to bring your games to a broader audience and platform.

CTA Small Image
FREE COURSES AT ZENVA
LEARN GAME DEVELOPMENT, PYTHON AND MORE
ACCESS FOR FREE
AVAILABLE FOR A LIMITED TIME ONLY

Creating JSON Data in Godot 4

Creating JSON data is the first step in the process of utilizing JSON in your Godot applications. Let’s start by generating a simple JSON object. We’ll create a Dictionary in Godot, which is the equivalent of an object in JSON.

var player_info = {
    "name": "The Wanderer",
    "level": 3,
    "health": 100,
    "items": ["sword", "shield", "potion"]
}

var json_string = JSON.print(player_info)
print(json_string)

This snippet creates a Dictionary representing a player, with a name, level, health and an array of items, then converts it to a JSON string using JSON.print(). When printed, you’ll see the JSON representation of your dictionary.

Now, let’s create a more complex JSON structure with nested objects and arrays:

var game_data = {
    "player": {
        "name": "The Wanderer",
        "level": 3,
        "health": 100
    },
    "inventory": {
        "items": ["sword", "shield"],
        "gold": 150
    },
    "enemies": [
        {"type": "goblin", "health": 50},
        {"type": "troll", "health": 150}
    ]
}

var complex_json_string = JSON.print(game_data)
print(complex_json_string)

In this example, we’ve created a more complex Dictionary with nested Dictionaries and Arrays, all of which will neatly convert into a JSON string that represents our game data structure.

Parsing JSON Data in Godot 4

Parsing JSON data converts a JSON text into Godot Dictionaries and Arrays. Let’s take the JSON string from our first example and convert it back into a Dictionary:

var parsed_data = JSON.parse(json_string).result
print(parsed_data)

Using JSON.parse() we can turn the JSON string back into a usable Godot Dictionary. The .result property contains the actual parsed data.

Sometimes JSON parsing can fail, for instance, due to a formatting error. In such cases, it’s important to check for errors during the parse operation:

var json_string_with_error = '{"name": "The Wanderer", level": 3, "health": 100}'
var parse_result = JSON.parse(json_string_with_error)

if parse_result.error == OK:
    print("Parsed Data:", parse_result.result)
else:
    print("Error:", parse_result.error_string)

This code attempts to parse a malformed JSON string. If there’s an error, it prints the error message; otherwise, it prints the parsed data.

Reading and Writing JSON to Files in Godot 4

Saving data to files is crucial for game persistence. In the next examples, we’ll save our JSON string to a file and then read it back into the game:

# Save JSON data to a file
var file = File.new()
file.open("user://player_info.json", File.WRITE)
file.store_string(json_string)
file.close()

This snippet saves the JSON string to a file in the user directory, which is platform-independent and generally used for storing user data.

To read the JSON data back from the file, we do the following:

# Read JSON data from a file
var file = File.new()
if file.open("user://player_info.json", File.READ) == OK:
    var read_data = file.get_as_text()
    file.close()
    
    var player_info = JSON.parse(read_data).result
    print(player_info)
else:
    print("Failed to read file")

This code block opens the JSON file, reads its content as text, and converts it back into a Dictionary using JSON.parse(). If the file cannot be read, it will print out an error message.

By mastering these basic operations, you can now create, parse, save, and load JSON data within Godot 4, forming a solid foundation for managing game data.

Leveraging JSON for game settings is a common practice. Imagine you want to store game settings like screen resolution, sound volume, and controls configuration. Here’s how you’d do just that using JSON:

var settings = {
    "screen_resolution": {"width": 1920, "height": 1080},
    "sound_volume": 0.5,
    "controls": {"jump": "SPACE", "move_left": "A", "move_right": "D"}
}

var settings_json = JSON.print(settings, " ", 4) # Indented for readability
file.open("user://settings.json", File.WRITE)
file.store_string(settings_json)
file.close()

In this snippet, we used JSON.print() with indentation options to create a more human-readable JSON string before writing it to a file. This can be especially useful when you want to manually edit the file for quick testing or configuration changes.

Godot also facilitates the deserialization of JSON data, allowing for easy access to specific values within a nested structure. For example, let’s say you want to access the “move_left” control setting:

var settings_data = JSON.parse(settings_json).result
var move_left_key = settings_data["controls"]["move_left"]
print("Move left is bound to:", move_left_key)

This will output the corresponding control key for moving left, demonstrating how to navigate and extract specific data from complex JSON structures.

But JSON isn’t just for static data. You can dynamically create JSON data by incorporating user input. Below is a method to update the player’s name and serialize it again:

func update_player_name(new_name):
    player_info["name"] = new_name
    var updated_json = JSON.print(player_info)
    # You would then write this back to a file or use it as needed

This function takes a new name as input, updates the player_info dictionary, and then creates a new JSON string with the updated data.

Error handling in Godot’s JSON parsing is worth exploring further. A common approach is to use the error enumeration provided by the JSONParseResult to identify specific issues:

var result = JSON.parse(json_string_with_error)

match result.error:
    JSONParseResult.OK:
        print("JSON parsed successfully:", result.result)
    JSONParseResult.ERR_FILE_CORRUPT:
        print("JSON file is corrupt")
    JSONParseResult.ERR_FILE_MISSING:
        print("JSON file is missing")
    _:
        print("Unknown error occurred:", result.error_string)

This code uses a match statement to handle different parse error types, offering granular control over error management and user feedback.

Dealing with JSON arrays is also essential. The following example shows how to loop through an array of items in a parsed JSON object:

var inventory_json = '{"items": ["sword", "shield", "potion"]}'
var inventory_data = JSON.parse(inventory_json).result

for item in inventory_data["items"]:
    print("You have a(n):", item)

This code extracts the “items” array from the parsed JSON data and prints each item, demonstrating how to handle arrays found within JSON data in Godot.

Finally, let’s talk about updating JSON data structures. If you have a large object and only need to update a single value, you may want to update the JSON string directly. Here’s how to approach this:

var player_json = '{"level": 3, "health": 100, "mana": 50}'
var player_data = JSON.parse(player_json).result

# Increase the player's level
player_data["level"] += 1

# Convert back to JSON string
var updated_player_json = JSON.print(player_data)
file.open("user://player_info.json", File.WRITE)
file.store_string(updated_player_json)
file.close()

This code snippet illustrates how to parse a JSON string, modify the data, and write the updated JSON back to a file. You can use similar approaches to manage any aspect of your game’s data dynamically as the game state changes.

With these practical examples, we hope you have gained a clearer understanding of how JSON can be utilized within Godot 4 for a variety of game development needs. Its versatility in storing, transferring, and managing data makes JSON an invaluable tool in your development arsenal, and we at Zenva are excited to help you harness its full potential.

When your game involves complex data like skill trees or crafting recipes, JSON becomes even more powerful. Let’s take a look at how you might handle a skill tree data structure in JSON:

var skill_tree = {
    "skills": [
        {
            "name": "Fireball",
            "level_requirement": 1,
            "mana_cost": 10
        },
        {
            "name": "Ice Shard",
            "level_requirement": 2,
            "mana_cost": 12,
            "prerequisites": ["Fireball"]
        }
    ]
}

var skill_tree_json = JSON.print(skill_tree)

This code snippet demonstrates how to define a skill tree as a JSON-compliant structure ready to be serialized. Storing this type of data in JSON makes it easy to manage and update as the game evolves.

One key aspect of using JSON in Godot 4 is understanding how to iterate over JSON arrays after parsing. This is particularly useful when loading complex data like the aforementioned skill tree:

var parsed_skill_tree = JSON.parse(skill_tree_json).result
for skill in parsed_skill_tree["skills"]:
    if skill["level_requirement"] <= player_level:
        print("Skill available: " + skill["name"])

This piece of code demonstrates iterating over the “skills” array and checks against the player’s level to determine skill availability.

Moving on to hand-crafting a JSON string can be error-prone. Thus, it’s always better to build a Dictionary or Array and then serialize it using JSON.print(). Below is an incorrect JSON string and how an error is handled:

var malformed_json = '{name: "Kai", class: "Warrior", level: 30}'
var result = JSON.parse(malformed_json)

if result.error != OK:
    push_error("Failed to parse JSON: " + result.error_string)

This example highlights how you would handle a situation where JSON data is incorrectly formatted, providing useful feedback for debugging purposes.

Using JSON for localizing your game is another advanced use case. Languages can be represented as JSON objects, making them easy to switch on the fly:

var localization_data = {
    "en": {
        "greeting": "Hello, player!",
        "farewell": "Goodbye!"
    },
    "es": {
        "greeting": "¡Hola, jugador!",
        "farewell": "¡Adiós!"
    }
}

func get_localized_text(language_code, key):
    var loc_json = JSON.print(localization_data)
    var loc_data = JSON.parse(loc_json).result
    return loc_data[language_code][key]

This function, `get_localized_text`, simplifies the process of fetching localized strings using the language code and key, illustrating JSON’s role in internationalization efforts.

JSON can also be used to configure procedural generation parameters. For instance, when generating a random dungeon, you might store tilesets and rules in JSON:

var dungeon_config = {
    "tilesets": ["dungeon", "cave", "fortress"],
    "size": {"width": 50, "height": 50},
    "rules": {
        "max_enemies_per_room": 5,
        "treasure_probability": 0.3
    }
}

var dungeon_config_json = JSON.print(dungeon_config)

Such configurational JSON provides a flexible way to adjust your procedural generation algorithms without hardcoding values, allowing for easy experimentation and tweaking.

Imagine your game features customizable characters. Using JSON lets players save and share their creations easily:

func save_character_data(character):
    var character_dict = {
        "name": character.name,
        "appearance": {
            "hair_color": character.hair_color,
            "armor_type": character.armor_type
        },
        "stats": {
            "strength": character.strength,
            "agility": character.agility
        }
    }
    var character_json = JSON.print(character_dict)
    # Save to file or external service

This function converts character data into a dictionary and then to a JSON string, ready to be saved or transferred.

Likewise, upon game start, you might want character data to be read and applied:

func load_character_data():
    # This would typically be read from a file or external service
    var character_json = '{"name": "Aria", "appearance": {"hair_color": "red", "armor_type": "leather"}, "stats": {"strength": 10, "agility": 8}}'
    var character_data = JSON.parse(character_json).result
    # Apply loaded data to character object
    character.name = character_data["name"]
    character.hair_color = character_data["appearance"]["hair_color"]
    character.armor_type = character_data["appearance"]["armor_type"]
    character.strength = character_data["stats"]["strength"]
    character.agility = character_data["stats"]["agility"]

This function showcases how to parse character data from a JSON string into game object properties, hence ensuring continuity for players across sessions.

Integrating JSON into your Godot projects isn’t just a feature, it’s a means to structure and manipulate game data with elegance and simplicity. Whether you’re dealing with simple key-value pairs or complex hierarchical data, JSON’s versatility is bound to enhance your development experience. At Zenva, our aim is to arm you with the knowledge to fully leverage these tools, helping you create robust and dynamic games with confidence.

Continue Your Game Development Journey with Zenva

Empowered with an understanding of JSON in Godot 4, where can you take your newfound skills? At Zenva, we know that learning is a continuous adventure, and we’re here to support your growth every step of the way. Take the next leap forward by exploring the Godot Game Development Mini-Degree. This collection of courses will guide you through the process of building cross-platform games and equip you with a portfolio of projects demonstrating your expanding expertise.

Whether you’re a beginner eager to dive into game development or a seasoned developer polishing your skills, our project-based courses are designed to be accessible, flexible, and packed with practical knowledge. You’ll not only learn core concepts, but also how to apply them to create mechanics for RPGs, RTS games, survival games, and platformers, among others. By mastering the free and open-source Godot engine, you’re setting yourself up for success.

As you continue to level up, don’t forget to check out our broader range of Godot courses to find the perfect match for your learning objectives. With our courses, you have the opportunity to learn coding, create engaging games, earn certificates, and build a foundation that can support your dreams, whether that’s publishing games, landing your ideal job, or launching your own business. So, why wait? The next chapter of your game development story is ready to be written with Zenva.

Conclusion

In your journey through Godot 4 and JSON, you’ve unlocked a treasure trove of tools to enhance your game’s data management and expand its capabilities. Embrace the power of JSON to save game states, manage settings, and even create dynamic, interactive experiences for your players. But the adventure doesn’t stop here. Continue to forge your path in game development with our Godot Game Development Mini-Degree, where you will transform theoretical knowledge into tangible skills that bring your imaginations to life.

We at Zenva are excited to be a part of your learning story, to witness your growth into a skilled developer, and to offer you all the resources you need. The world of game development is vast and full of opportunities – and it’s yours to explore. So what are you waiting for? Take the next step in your game creation journey with Zenva and make your mark in the gaming industry!

FREE COURSES
Python Blog Image

FINAL DAYS: Unlock coding courses in Unity, Godot, Unreal, Python and more.