GDScript Json Tutorial – Complete Guide

There is no denying that game development is an exciting field. For budding game developers, learning different aspects of coding and game mechanics is not only essential, but also enriching. One integral part of this learning is getting a good grip on handling GDScript JSON in the Godot Game Engine, a popular technology used to develop both 2D and 3D games.

What is GDScript JSON?

GDScript is the built-in scripting language of the Godot Game Engine. It is designed specifically to be easy to learn for beginners, yet powerful enough to develop complex games. JSON, standing for JavaScript Object Notation, is a lightweight data-interchange format that’s easy for humans to read and for machines to parse and generate.

What is it for and Why Should I Learn It?

GDScript JSON is extensively used to save your game’s data in a structured and easily retrievable format. It can also be used to consume APIs provided by third party services such as high scores, player management, and more.

Learning GDScript JSON is advantageous for several reasons:

  • It’s straightforward and easy to use, perfectly matching with the simplicity of GDScript.
  • It enables the game to be dynamic and user-oriented. You can save the player’s data like scores, levels etc., in a JSON file and use it across different sessions.
  • It facilitates integration with web services providing player statistics, ad analytics, etc. in JSON format.

With the right guidance and ample practice, mastering GDScript JSON can effectively elevate your game development prowess, thus making your games more engaging, user-friendly, and dynamic.

CTA Small Image

FREE COURSES AT ZENVA

LEARN GAME DEVELOPMENT, PYTHON AND MORE

AVAILABLE FOR A LIMITED TIME ONLY

Basics of GDScript JSON in Godot Game Engine

In Godot, we can read and write JSON with easy-to-use GDScript commands. Let’s dive into it with some practical examples.

Writing JSON in GDScript

Assuming we have a dictionary representing a player’s data:

var my_dictionary = {
    "player_name": "John",
    "player_score": 1000,
    "player_levels": [1, 2, 3, 4, 5]
}

To convert this dictionary to a JSON string, we use the to_json function:

var my_json_string = JSON.to_json(my_dictionary)

Saving JSON Data to a File

Next, often we’ll want to save these JSON data to a file, thus ensuring persistence between game sessions. Here’s how we do it:

var file = File.new()
file.open("user://player_data.json", File.WRITE)
file.store_string(my_json_string)
file.close()

Reading JSON from a File

With our player’s data stored as a JSON file, it’s time to read it. We’ll use the File class to read the file’s content:

var file = File.new()
file.open("user://player_data.json", File.READ)
var json_string = file.get_as_text()
file.close()

Converting JSON String into GDScript Dictionary

Last but not least, to access the previously saved JSON data, we convert the JSON string back to a dictionary:

var dictionary = JSON.parse(json_string).result

Using the above examples, you can effectively manage, save, and retrieve game data in the Godot Engine using GDScript JSON. Stay tuned for our next part where we’ll delve deeper into manipulating JSON arrays and objects.

Working with JSON Arrays

Often, your data will include arrays. Let’s look at how you can handle JSON arrays using GDScript.

Consider a game scenario where you want to store the levels completed by a player. We store these in an array:

var level_array = [1, 2, 3, 4, 5]

To convert this array into a JSON string, use the to_json function:

var json_string = JSON.to_json(level_array)

And similar to the previous example, to convert the JSON string back to a GDScript array:

var my_array = JSON.parse(json_string).result

Working with JSON Objects

JSON objects or dictionaries in GDScript are collections of key-value pairs. These are comparable to Python’s dictionaries or JavaScript’s objects.

Let’s consider you have an object with player’s details:

var player_object = {
    "name": "John",
    "score": 1000,
    "completed_levels": [1, 2, 3, 4, 5]
}

Just as before, we can convert this object into a JSON string and vice versa:

var json_string = JSON.to_json(player_object)
var my_object = JSON.parse(json_string).result

Nested JSON Data

Sometimes, data can be in nested JSON format with multiple layers of dictionaries. Here’s how to navigate through nested keys and values:

var player_object = {
    "player": {
        "name": "John",
        "score": 1000
    },
    "completed_levels": [1, 2, 3, 4, 5]
}

To access the player’s name and score in the nested dictionary, use:

var name = player_object["player"]["name"]
var score = player_object["player"]["score"]

With these fundamental GDScript JSON coding techniques, you can store and handle complex game data in the Godot engine with ease. Practice these concepts on real-life game scenarios and take your game development skills to the next level!

Editing JSON Data

Once you’ve mastered accessing JSON data, it’s valuable to also understand how to modify it. Here’s how you can add, delete, and edit JSON data in GDScript.

Adding Data to JSON

To add a new data point to our player object, assign a value to a new key:

player_object["player"]["health"] = 100

This will add a new key-value pair “health”: 100, to the player object.

Modifying JSON Data

To update the value of a specific key, simply reassign a new value:

player_object["player"]["score"] = 1200

This will update the player’s score to 1200.

Deleting JSON Data

To remove a particular key-value pair from your JSON object, use the erase method:

player_object["player"].erase("health")

This will remove the health data from the player object.

Working With Multi-Dimensional Arrays

A multi-dimensional array can be used to store complex data such as a grid of tiles or a set of items each with their own properties. Here’s an example:

var multi_array = [[1, "Sword"], [2, "Shield"], [3, "Potion"]]

Converting this to a JSON string and back can be done just like in our previous examples:

var json_string = JSON.to_json(multi_array)
var my_multi_array = JSON.parse(json_string).result

With these advanced data handling techniques, you’re now better equipped to manage complex scenarios in your game development journey. Remember, the key to mastering GDScript JSON lies in continuous practice and curiosity to experiment with diverse data structures.

Where to Go Next

Now that you’ve dipped your toes into the fascinating world of GDScript JSON, there is a vast ocean of knowledge waiting for you. At Zenva, we are committed to guiding you to become an accomplished game developer, and so we invite you to take the leap and dive into our expansive selection of tools and resources on game development.

The Godot Game Development Mini-Degree at Zenva Academy presents a comprehensive collection of courses intended to nurture your game-building skills using the Godot 4 engine. Crafted by experienced instructors, the curriculum covers various facets of both 2D and 3D game development and can easily cater to beginners as well as seasoned developers.

For delving into a broader spectrum, do check out our entire collection of Godot Courses. Here at Zenva, our belief is that continuous learning fuels progress, and we strive to empower you with high-quality content to boost your career. From beginner to professional, we’ve got you covered. Embrace the journey and keep learning!

Conclusion

Mastering the manipulation of GDScript JSON is a valuable skill in your game development journey. It not only empowers you to handle diverse and dynamic game data but also opens doors to a myriad of possibilities in terms of user engagement and game mechanics.

Take your newfound GDScript JSON knowledge to the next level and deepen your understanding of game development with our Godot Game Development Mini-Degree. Remember, at Zenva, we’re passionate about making your learning journey as interactive and enriching as possible. So keep learning, keep growing, and let’s create some fantastic games together!

FREE COURSES

Python Blog Image

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