To expand on @pault comment, you could use try/except, but it would work better in a better indented blocks (optionally, you can also chain the with statement):

from json.decoder import JSONDecodeError

with open(filename, 'a+') as infile, open(filename, 'w') as outfile:
    try:
        old_data = json.load(infile)
        data = old_data + obj
        json.dump(data, outfile)
    except JSONDecodeError:
        pass
Answer from Sazzy on Stack Overflow
🌐
Python Forum
python-forum.io › thread-27694.html
empty json file error
I wrote this and since it creates an empty file it give me an error. with open("food.json", "r+") as file: food = json.load(file)Error:Traceback (most recent call last): File "c:/Users/User/MyStuff/ml
Discussions

python - Forcing json to dump a json object even when list is empty - Stack Overflow
In the case where the list is non-empty, this works fine and my next script reads in the json file. But when the list is empty, I get "ValueError: No JSON object could be decoded." This makes sense, because when I open the file, there is indeed no content and thus no JSON object. More on stackoverflow.com
🌐 stackoverflow.com
arrays - Appending into an empty JSON file in python - Stack Overflow
I already have a JSON file which I am parsing using Python 2.7 and I want to dump the parsed out data into another empty JSON file. I am using a for-loop to parse out the data from the old JSON fil... More on stackoverflow.com
🌐 stackoverflow.com
Python writes empty json file - Stack Overflow
I'm working on a console app in python. I have a command that should save the program state as a json file, but when I write the file, it's empty. The result of .as_list() here is a list containing... More on stackoverflow.com
🌐 stackoverflow.com
Python: Json file become empty - Stack Overflow
When openning a file with the "w" parameter, everytime you will write to it, the content of the file will be erased. (You will actually replace what's written already). Not sure if this is what you are looking for, but could be one of the reasons why "cam_settings.json" becomes empty after the ... More on stackoverflow.com
🌐 stackoverflow.com
🌐
Stack Overflow
stackoverflow.com › questions › 65556852 › appending-into-an-empty-json-file-in-python
arrays - Appending into an empty JSON file in python - Stack Overflow
Your current code fails because you can't write a python dictionary (f.write(entry)) without some sort of serialization. After reading the JSON list, you could filter it and write it again. You don't need the extra complication of indexing the list you read, just iterate it. And since you want to write the entire record, you don't need to create a new dictionary. with open("output_log.json") as f: json_ob = json.load(f) entries = [] for entry in json_ob: if (re.search(r"\s", entry["name"]) and ("444" in entry["title"]) and (r"https://robotics.com/projects/" in entry["body"])): entries.append(entry) with open("cumulative_output.json", "w") as f: json.dump(entries)
🌐
OneUptime
oneuptime.com › home › blog › how to read and write json files in python
How to Read and Write JSON Files in Python
January 25, 2026 - import json from pathlib import Path def safe_load_json(filepath): """Safely load JSON with comprehensive error handling.""" path = Path(filepath) if not path.exists(): raise FileNotFoundError(f"File not found: {filepath}") if not path.is_file(): raise ValueError(f"Path is not a file: {filepath}") try: with open(path, 'r', encoding='utf-8') as file: content = file.read() # Handle empty files if not content.strip(): return {} return json.loads(content) except json.JSONDecodeError as e: raise ValueError(f"Invalid JSON in {filepath}: {e}") except PermissionError: raise PermissionError(f"Permission denied reading: {filepath}") # Usage try: data = safe_load_json('config.json') except (FileNotFoundError, ValueError, PermissionError) as e: print(f"Error loading config: {e}") data = {}
🌐
freeCodeCamp
freecodecamp.org › news › loading-a-json-file-in-python-how-to-read-and-parse-json
Loading a JSON File in Python – How to Read and Parse JSON
July 25, 2022 - This is because null is not valid in Python. The json module also has the load method which you can use to read a file object and parse it at the same time. Using this method, you can update the previous code to this: import json with open('user.json') as user_file: parsed_json = json.load(user_file) print(parsed_json) # { # 'name': 'John', # 'age': 50, # 'is_married': False, # 'profession': None, # 'hobbies': ['travelling', 'photography'] # }
🌐
Real Python
realpython.com › python-json
Working With JSON Data in Python – Real Python
August 20, 2025 - In lines 3 to 22, you define a dog_data dictionary that you write to a JSON file in line 25 using a context manager. To properly indicate that the file contains JSON data, you set the file extension to .json. When you use open(), then it’s good practice to define the encoding.
Find elsewhere
🌐
Pythonguru
pythonguru.in › home › post › json-file-io-operations-in-python › 071dde3f-6c05-420c-b0b4-22af25d6cddb
JSON File I/O Operations in Python
Learn Full stack Python with our Carrer Oriented Program at KPHB, Hyderabad. Also explore 1000+ Programming solutions for Real-time problems.
🌐
Upgrad
upgrad.com › home › tutorials › software & tech › how to open json file in python
Opening JSON Files in Python: A Step-by-Step Guide
June 21, 2026 - JSON files are a widely used format for storing and exchanging structured data, and Python provides a straightforward and powerful way to work with them. In this guide, we'll walk you through the process of opening, reading, and manipulating JSON files using Python's built-in capabilities.
🌐
Quora
quora.com › How-do-you-declare-an-empty-JSON-in-Python
How to declare an empty JSON in Python - Quora
Answer (1 of 4): JSON is a serialization format that can represent certain kinds of objects as strings. An empty string is not a valid JSON representation of anything. If you try to decode an empty string using Python's standard [code ]json[/code] module, you'll get an error: [code]>>> import j...
🌐
Scaler
scaler.com › home › topics › read, write, parse json file using python
Read, Write, Parse JSON File Using Python - Scaler Topics
April 17, 2024 - Let's consider an example where ... holds the data we want to write to the file. We open a file named user_data.json in write mode ('w')....
🌐
Programiz
programiz.com › python-programming › json
Python JSON: Read, Write, Parse JSON (With Examples)
To write JSON to a file in Python, we can use json.dump() method. import json person_dict = {"name": "Bob", "languages": ["English", "French"], "married": True, "age": 32 } with open('person.txt', 'w') as json_file: json.dump(person_dict, json_file)
🌐
CodeRivers
coderivers.org › blog › python-open-json-file
Python: Opening and Working with JSON Files - CodeRivers
February 22, 2026 - In this example: 1. We use the open function to open the file in read mode ('r'). 2. The json.load function reads the JSON data from the file object and converts it into a Python data structure (usually a dictionary or a list).
🌐
Reddit
reddit.com › r/learnpython › json.loads crashes whenever there’s an empty string, how can i make json.loads return nothing instead of crash?
r/learnpython on Reddit: Json.loads crashes whenever there’s an empty string, how can i make json.loads return nothing instead of crash?
January 9, 2020 - Subreddit for posting questions and asking for general advice about your python code. ... “” or null , I guess, really everything but crashing is good even default value like “error” ... You could make your own wrapper around json.loads that checks if the input string is empty first and returns whatever you want.