Python JSON Help

Question:
I will be making a Text Based RPG template and it will be using JSON to save all the stats globally, but I can’t seem to get it to work.

Repl link:
https://replit.com/@SalladShooter/Text-Based-RPG#main.py

import pyfiglet
from replit import clear
import os
import json

# Colors ->
BLACK = "\033[0;30m"
RED = "\033[0;31m"
GREEN = "\033[0;32m"
BROWN = "\033[0;33m"
BLUE = "\033[0;34m"
PURPLE = "\033[0;35m"
CYAN = "\033[0;36m"
LIGHT_GRAY = "\033[0;37m"
DARK_GRAY = "\033[1;30m"
LIGHT_RED = "\033[1;31m"
LIGHT_GREEN = "\033[1;32m"
YELLOW = "\033[1;33m"
LIGHT_BLUE = "\033[1;34m"
LIGHT_PURPLE = "\033[1;35m"
LIGHT_CYAN = "\033[1;36m"
WHITE = "\033[1;37m"
BOLD = "\033[1m"
FAINT = "\033[2m"
ITALIC = "\033[3m"
UNDERLINE = "\033[4m"
BLINK = "\033[5m"
NEGATIVE = "\033[7m"
CROSSED = "\033[9m"
END = "\033[0m"
# Background Colors ->
BACK_BLACK = "\u001b[40m"
BACK_RED = "\u001b[41m"
BACK_GREEN = "\u001b[42m"
BACK_YELLOW = "\u001b[43m"
BACK_BLUE = "\u001b[44m"
BACK_MAGENTA = "\u001b[45m"
BACK_CYAN = "\u001b[46m"
BACK_WHITE = "\u001b[47m"

PPC = "RPG"
ASCII = pyfiglet.figlet_format(PPC, font="big")
print(BOLD + ASCII + END)

# Load JSON data
SAVES_FILE = "SAVES.json"


def load_saves():
    try:
        with open(SAVES_FILE, "r") as f:
            return json.load(f)
    except FileNotFoundError:
        return {}


def save_saves(data):
    with open(SAVES_FILE, "w") as f:
        json.dump(data, f, indent=2)


username = os.environ["REPL_OWNER"]
saves_data = load_saves()

if username in saves_data:
    data = saves_data[username]
    print(f"{BOLD}{BLUE}{username}{END} in saves_data")
else:
    print(f"Welcome to {BOLD}RPG{END}! An adventurous text based game. With plenty of {BOLD}{RED}fighting{END} and {BOLD}{GREEN}puzzle solving{END}.")
    saves_data[username] = {}  # Initialize the new user's data
    save_saves(saves_data)

You are trying to load the JSON but your file is empty. When json.load() attempts to read from an empty file, it will raise an error (I don’t remember which error) because an empty file isn’t valid JSON format.

You have to adjust your code to handle the possibility that the file might be empty.

4 Likes

I could be wrong, but I think this will work for that:

return json.load(f if f else "{}")
1 Like

@Firepup650 It doesn’t work and gives me the same error as before (the one about JSON being empty).

@WindLother what exactly could I use to do that in this situation (I have tried ChatGPT and it can’t get it to work).

You can try create a content string. It reads the content of the file into the string, which we called content and then it checks if content is an empty string.

try:
        with open(SAVES_FILE, "r") as f:
            content = f.read()
            if not content:
                print(f"{SAVES_FILE} is empty. Initializing a new game state.")
                return {}
            return json.loads(content)
    except FileNotFoundError:
        print(f"{SAVES_FILE} not found. Creating a new one.")
        return {}
2 Likes

What’s the base format for the JSON?

It wouldn’t include the message, but using that I can compact it a tad bit more:

return json.loads(content) if content else {}
3 Likes

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.