TExcelTAD
Home › Game Development Roadmap & Fundamentals › Save & Load with JSON

Save & Load with JSON

A save file is a snapshot of the game state the player cares about: where they are, what they own, what they've done. Saving well is mostly about choosing what to save and planning for change: your game will get updates, and old save files must keep loading. JSON is the usual starting format because it's readable, easy to debug and supported everywhere.

What goes in a save

Save the minimum state needed to rebuild the game, not the objects themselves:

Save Don't save
level id, player position, health meshes, textures, the scene graph
inventory as item ids and counts full item definitions (name, icon, stats)
quest flags ("door_7_opened") anything you can recompute (derived stats, cached paths)
settings, play time references or pointers between objects

Item definitions live in the game's data; the save says "3 × potion_small". When you rebalance a potion in a patch, old saves pick up the new values automatically.

Save to a JSON string and load it back

System.Text.Json ships with .NET. A record holds the save data; serializing turns it into text, and deserializing turns text back into objects:

csharp · try it yourself
using System;
using System.Collections.Generic;
using System.Text.Json;

var save = new SaveData(
    Version: 1,
    Level: "forest_02",
    X: 12.5, Y: 3,
    Health: 74,
    Inventory: new Dictionary<string, int> { ["potion_small"] = 3, ["key_bronze"] = 1 },
    Flags: new List<string> { "door_7_opened", "met_blacksmith" });

var options = new JsonSerializerOptions { WriteIndented = true };
string json = JsonSerializer.Serialize(save, options);
Console.WriteLine(json);

SaveData loaded = JsonSerializer.Deserialize<SaveData>(json);
Console.WriteLine(
quot;Loaded: {loaded.Level} at ({loaded.X}, {loaded.Y}), {loaded.Health} HP, {loaded.Inventory["potion_small"]} potions"); record SaveData(int Version, string Level, double X, double Y, int Health, Dictionary<string, int> Inventory, List<string> Flags);
{
  "Version": 1,
  "Level": "forest_02",
  "X": 12.5,
  "Y": 3,
  "Health": 74,
  "Inventory": {
    "potion_small": 3,
    "key_bronze": 1
  },
  "Flags": [
    "door_7_opened",
    "met_blacksmith"
  ]
}
Loaded: forest_02 at (12.5, 3), 74 HP, 3 potions

In a real game you would write json to a file. Each engine has a per-user folder for that:

Engine Save folder Notes
Unity Application.persistentDataPath JsonUtility is built in but limited (no dictionaries); many projects use Newtonsoft Json.NET (Unity package com.unity.nuget.newtonsoft-json). PlayerPrefs is for small settings, not save games
Godot user:// FileAccess, JSON.stringify / JSON.parse_string, or ConfigFile for settings
Unreal Saved/SaveGames a USaveGame subclass with UGameplayStatics::SaveGameToSlot / LoadGameFromSlot

Plan for versions

After release you will add fields, rename things and change formats. Put a version number in every save and upgrade old saves step by step when loading. This is called migration:

csharp · try it yourself
using System;
using System.Text.Json;
using System.Text.Json.Nodes;

string oldSave = """{"Version":1,"Level":"forest_02","Gold":120}""";
string newerSave = """{"Version":2,"Level":"cave_01","Coins":{"gold":40,"gems":2}}""";

Console.WriteLine(Migrate(oldSave));
Console.WriteLine(Migrate(newerSave));

static string Migrate(string json)
{
    var data = JsonNode.Parse(json)!.AsObject();
    int version = (int)data["Version"]!;

    if (version == 1)                       // v1 -> v2: Gold became Coins.gold, gems added
    {
        int gold = (int)data["Gold"]!;
        data.Remove("Gold");
        data["Coins"] = new JsonObject { ["gold"] = gold, ["gems"] = 0 };
        version = 2;
    }
    if (version == 2)                       // v2 -> v3: new setting with a default
    {
        data["Difficulty"] = "normal";
        version = 3;
    }
    data["Version"] = version;
    return data.ToJsonString();
}
{"Version":3,"Level":"forest_02","Coins":{"gold":120,"gems":0},"Difficulty":"normal"}
{"Version":3,"Level":"cave_01","Coins":{"gold":40,"gems":2},"Difficulty":"normal"}

Each if upgrades exactly one version, and they run in a chain, so a v1 save goes through every step. Never delete an old migration step: someone will load a two-year-old save.

Never trust a save file

Save files get corrupted (power loss mid-write, full disks, cloud sync conflicts) and edited by players. Loading must fail gracefully, never crash the game or wipe progress:

csharp · try it yourself
using System;
using System.Text.Json;

string[] files =
{
    """{"Level":"forest_02","Health":74}""",
    """{"Level":"forest_02","Health":""",          // truncated: power loss during the write
    """{"Level":"forest_02","Health":-500}""",     // edited or buggy value
};

foreach (string text in files)
    Console.WriteLine(TryLoad(text));

static string TryLoad(string text)
{
    try
    {
        var save = JsonSerializer.Deserialize<Save>(text);
        if (save is null || save.Level is null) return "invalid: missing data, using backup";
        int health = Math.Clamp(save.Health, 1, 100);
        return 
quot;ok: {save.Level}, health {health}{(health != save.Health ? " (clamped)" : "")}"; } catch (JsonException) { return "corrupt: could not parse, using backup"; } } record Save(string Level, int Health);
ok: forest_02, health 74
corrupt: could not parse, using backup
ok: forest_02, health 1 (clamped)

Practical rules:

  1. Write safely. Write to a temporary file, then replace the real file in one step; keep the previous save as a backup. A crash mid-write then leaves the old save intact.

    csharp
    File.WriteAllText(path + ".tmp", json);
    if (File.Exists(path)) File.Replace(path + ".tmp", path, path + ".bak");
    else File.Move(path + ".tmp", path);
  2. Validate on load: clamp numbers, ignore unknown item ids, fall back to defaults for missing fields.

  3. Don't treat JSON as security. Players can edit a single-player save, and that's usually fine. Anything that matters for fairness (multiplayer, leaderboards, purchases) belongs on a server.

  4. Save at safe moments: checkpoints, menus, level transitions. Saving mid-combat is where most "my save is broken" bugs come from.

Test yourself

What should a save file store for the player's inventory?

  1. Full item objects with icons and stats
  2. Item ids and counts
  3. Memory addresses of the items
  4. Nothing; recompute it

Why put a version number in every save file?

  1. For copyright
  2. So the game can migrate older formats step by step after updates
  3. To encrypt the file
  4. JSON requires it

What is the safe way to overwrite a save file?

  1. Open it and write over it directly
  2. Write a temporary file, then replace the original (keeping a backup)
  3. Delete it first, then write
  4. Write it twice