Python add data into a JSON file

Python add data into a JSON file

Here is a little script that create a dictionary (a type of array) in Python and this dictionary creates a JSON-file. This JSON file you can use for example for Python Pandas.

import json
from os import path

# --- FUNCTION: DATA COLLECTION ---

def erfasse_personen_daten():
    """Captures name, age and city for multiple persons from the user."""
    alle_personen = []  # Eine Liste, um alle Personen-Dictionaries zu speichern
    
    print("\n--- Start data collection ---")

    while True:
        print("\n--- Insert new person ---")
        
        name = input("name (or 'fertig' in order to stop the script): ")
        
        # termination condition
        if name.lower() == 'fertig':
            break
            
        alter = input("Alter: ")
        stadt = input("Stadt: ") # z.B. Fußgönheim
        
        # Ein Dictionary für die aktuelle Person erstellen
        neue_person = {
            "Name": name,
            "Alter": alter,
            "Stadt": stadt
        }
        
        # Add the dictionary to the list
        alle_personen.append(neue_person)
        
    return alle_personen

# --- Main program ---

# 1. Query file names
dateiname = input("Bitte geben Sie den Dateinamen (ohne .json) ein: ")
file_name_with_ext = dateiname + ".json"

# 2. CHECK IF THE FILE TO BE READ IS PRESENT
if path.exists(file_name_with_ext):
    print(f"\n✅ Datei '{file_name_with_ext}' gefunden. Lese Inhalt...")

    # Read data
    try:
        # Use UTF-8 when reading
        with open(file_name_with_ext, "r", encoding="utf-8") as f:
            print("\n--- Inhalt der vorhandenen Datei ---")
            
            # To load the JSON as a Python list/dictionary:
            data_object = json.load(f)
            
            print(f"Erster Eintrag (Python-Objekt): {data_object[0]}")
            print(f"Gesamte Anzahl Datensätze: {len(data_object)}")
            
            # If you only want to see the raw content:
            # f.seek(0) # Zurück zum Anfang der Datei
            # print(f.read()) 
            
    except json.JSONDecodeError:
        print("❌ Fehler: Datei existiert, aber das JSON-Format ist ungültig.")
    except Exception as e:
        print(f"❌ Fehler beim Lesen der Datei: {e}")
        
else:
    # 3. FILE DOES NOT EXIST, so we ENTER new data
    print(f"\n⚠️ Datei '{file_name_with_ext}' nicht gefunden. Starte Datenerfassung...")
    
    # Collect data from the user
    gesammelte_daten = erfasse_personen_daten()
    
    # Once data has been collected, store it
    if gesammelte_daten:
        print(f"\n✅ {len(gesammelte_daten)} Datensätze erfasst. Speichere...")
        
        # Convert data to a JSON string
        # ensure_ascii=False for correct umlauts (Fußgönheim, Ä, Ö, Ü)
        json_output = json.dumps(
            gesammelte_daten, 
            indent=3, 
            ensure_ascii=False
        )
        
        # WRITE data (create file)
        try:
            # Use UTF-8 when writing
            with open(file_name_with_ext, "w", encoding="utf-8") as f:
                f.write(json_output)
            print("✅ Datei erfolgreich erstellt und gespeichert.")
            
        except Exception as e:
            print(f"❌ Fehler beim Erstellen der Datei: {e}")
    else:
        print("ℹ️ Keine Daten erfasst. Datei wurde nicht erstellt.")
Die Kommentare sind geschlossen.