json might not be the best choice for on-disk formats; The trouble it has with appending data is a good example of why this might be. Specifically, json objects have a syntax that means the whole object must be read and parsed in order to understand any part of it.

Fortunately, there are lots of other options. A particularly simple one is CSV; which is supported well by python's standard library. The biggest downside is that it only works well for text; it requires additional action on the part of the programmer to convert the values to numbers or other formats, if needed.

Another option which does not have this limitation is to use a sqlite database, which also has built-in support in python. This would probably be a bigger departure from the code you already have, but it more naturally supports the 'modify a little bit' model you are apparently trying to build.

Answer from SingleNegationElimination on Stack Overflow
Top answer
1 of 12
106

json might not be the best choice for on-disk formats; The trouble it has with appending data is a good example of why this might be. Specifically, json objects have a syntax that means the whole object must be read and parsed in order to understand any part of it.

Fortunately, there are lots of other options. A particularly simple one is CSV; which is supported well by python's standard library. The biggest downside is that it only works well for text; it requires additional action on the part of the programmer to convert the values to numbers or other formats, if needed.

Another option which does not have this limitation is to use a sqlite database, which also has built-in support in python. This would probably be a bigger departure from the code you already have, but it more naturally supports the 'modify a little bit' model you are apparently trying to build.

2 of 12
54

You probably want to use a JSON list instead of a dictionary as the toplevel element.

So, initialize the file with an empty list:

with open(DATA_FILENAME, mode='w', encoding='utf-8') as f:
    json.dump([], f)

Then, you can append new entries to this list:

with open(DATA_FILENAME, mode='w', encoding='utf-8') as feedsjson:
    entry = {'name': args.name, 'url': args.url}
    feeds.append(entry)
    json.dump(feeds, feedsjson)

Note that this will be slow to execute because you will rewrite the full contents of the file every time you call add. If you are calling it in a loop, consider adding all the feeds to a list in advance, then writing the list out in one go.

🌐
GeeksforGeeks
geeksforgeeks.org › python › append-to-json-file-using-python
Append to JSON file using Python - GeeksforGeeks
July 1, 2026 - import json new_employee = { "name": ... reads the existing JSON data into a Python dictionary. The append() method adds the new employee record to the employees list, and json.dump() writes the updated data back to the ...
Discussions

How to append an dictionary into a json file?
Your problem is not appending strings/jsons to a file. Your problem is later on reading it. json files usually hold ONE json object, not many concatenated objects. You can create a list, and have you dictionaries be items in that list, and then append to it, and dump the entire list as JSON to have multiple dictionaries stored, but eventually its one JSON object. If you want to modify/append a json object in a file, you read it first, load/loads, change it however you want, and write it back. # load it with open("index.json" , "r") as json_file: file_data = json.loads(json_file.read()) # change it file_data.append(dict) # write it all back with open("index.json" , "w") as json_file: json_file.write(json.dumps(file_data)) (Obviously above code assumes you already have a list dumped as a json object in index.json) More on reddit.com
🌐 r/learnpython
2
1
September 2, 2023
create and append data in json format to json file - python - Stack Overflow
You can't modify the json content like that. You'll need to modify the data structure and then completely rewrite the json file. You might be able to just read the data from jsone at startup, and write it at shutdown. More on stackoverflow.com
🌐 stackoverflow.com
python - Append JSON to file - Stack Overflow
I am trying to append values to a json file. How can i append the data? I have been trying so many ways but none are working ? Code: def all(title,author,body,type): title = "hello" auth... More on stackoverflow.com
🌐 stackoverflow.com
python - Append data to json file - Stack Overflow
For me it was complicated yes, because im learning Python and touching json the first time in my life. Isn't it bad to load the file and its content every time to parse them back then? What if i have for example 9999 Items in the "user" list. Isn't there a method to just append an item to the ... More on stackoverflow.com
🌐 stackoverflow.com
🌐
Python.org
discuss.python.org › python help
Appending JSON to same file - Python Help - Discussions on Python.org
January 5, 2023 - Hi, I need to make that within each request from api new dict will be appended to json. Now I have that each time data overwritten, but I need to append to existing file. How to achieve this? Code:(import requestsimport jsonimport timeimport csvimport pandas start=2 - Pastebin.com)
🌐
CodeSpeedy
codespeedy.com › home › append to json file in python
Append to JSON file in Python - CodeSpeedy
July 3, 2020 - 1.loads(): purpose of loads() is to parse the JSON string. It takes JSON string as a parameter and returns the python dictionary object.
🌐
Finxter
blog.finxter.com › home › learn python blog › how to append data to a json file in python? [+video]
How to Append Data to a JSON File in Python? [+Video] - Be on the Right Side of Change
June 1, 2022 - Call json.load(file) to load the data from the file in your Python code. Now, you can update the data in your Python code. For example, if you JSON file is structured as a list of dictionaries, simply append a new dictionary.
🌐
Delft Stack
delftstack.com › home › howto › python › append data to a json file using python
How to Append Data to a JSON File Using Python | Delft Stack
February 2, 2024 - This tutorial demonstrates the use of Python dictionary and list to append data to a JSON file using Python.
Find elsewhere
🌐
HowToDoInJava
howtodoinjava.com › home › python json › python – append to json file
Python - Append to JSON File
December 9, 2022 - Learn to append JSON data into file in Python. To append, read the file to dict object, update the dict object and finally write the dict to the file.
🌐
Quora
quora.com › How-do-you-append-a-dictionary-to-a-JSON-file-Python
How to append a dictionary to a JSON file (Python) - Quora
Answer (1 of 3): [code]import json with open(r'Enter the full path name here ending with .json','w') as f: #The previous line will create the json file if doesn't exist Thing = {} Thing['stuff'] = [] Thing['stuff'].append({ 'Name' : 'John Doe', 'Age' : 35, 'Phone Number' : '123-4567...
🌐
YouTube
youtube.com › watch
How to Append Data to a JSON File in Python? - YouTube
Full Tutorial: https://blog.finxter.com/how-to-append-data-to-a-json-file-in-python/Email Academy: https://blog.finxter.com/email-academy/►► Do you want to t...
Published: May 29, 2021
🌐
YouTube
youtube.com › watch
How to Append JSON files in Python - YouTube
If you enjoy this video, please subscribe. I provide all my content at no cost. If you want to support my channel, please donate viaPayPal: https://www.payp...
Published: February 12, 2020
🌐
Bomberbot
bomberbot.com › python › mastering-json-file-manipulation-in-python-a-comprehensive-guide-to-appending-data
Mastering JSON File Manipulation in Python: A Comprehensive Guide to Appending Data - Bomberbot
June 20, 2025 - Python's json module provides a simple interface for working with JSON data. Here are the key functions we'll be using: json.load(): Deserialize JSON from a file-like object ... Let's start with a basic scenario: we have a JSON file containing a list of items, and we want to append a new item to this list.
Top answer
1 of 2
3

I suspect you left out that you're getting a TypeError in the blocks where you're trying to write the file. Here's where you're trying to write:

with open('offline_post.json','a') as f:
    new = json.loads(f)
    new.update(a_dict)
    json.dump(new,f)

There's a couple of problems here. First, you're passing a file object to the json.loads command, which expects a string. You probably meant to use json.load.

Second, you're opening the file in append mode, which places the pointer at the end of the file. When you run the json.load, you're not going to get anything because it's reading at the end of the file. You would need to seek to 0 before loading (edit: this would fail anyway, as append mode is not readable).

Third, when you json.dump the new data to the file, it's going to append it to the file in addition to the old data. From the structure, it appears you want to replace the contents of the file (as the new data contains the old data already).

You probably want to use r+ mode, seeking back to the start of the file between the read and write, and truncateing at the end just in case the size of the data structure ever shrinks.

with open('offline_post.json', 'r+') as f:
    new = json.load(f)
    new.update(a_dict)
    f.seek(0)
    json.dump(new, f)
    f.truncate()

Alternatively, you can open the file twice:

with open('offline_post.json', 'r') as f:
    new = json.load(f)
new.update(a_dict)
with open('offline_post.json', 'w') as f:
    json.dump(new, f)
2 of 2
0

This is a different approach, I just wanted to append without reloading all the data. Running on a raspberry pi so want to look after memory. The test code -

import os

json_file_exists = 0
filename = "/home/pi/scratch_pad/test.json"

# remove the last run json data
try:
    os.remove(filename)
except OSError:
    pass

count = 0
boiler = 90
tower = 78

while count<10:
    if json_file_exists==0:
        # create the json file
        with open(filename, mode = 'w') as fw:  
            json_string = "[\n\t{'boiler':"+str(boiler)+",'tower':"+str(tower)+"}\n]"
            fw.write(json_string)   
            json_file_exists=1
    else:
        # append to the json file
        char = ""
        boiler = boiler + .01
        tower = tower + .02
        while(char<>"}"):
            with open(filename, mode = 'rb+') as f: 
                f.seek(-1,2)
                size=f.tell()
                char = f.read()
                if char == "}":
                    break
                f.truncate(size-1)

        with open(filename, mode = 'a') as fw:  
            json_string = "\n\t,{'boiler':"+str(boiler)+",'tower':"+str(tower)+"}\n]"
            fw.seek(-1, os.SEEK_END)
            fw.write(json_string)

    count = count + 1
🌐
sqlpey
sqlpey.com › python › top-4-ways-to-append-data-to-a-json-file-in-python
Top 4 Ways to Append Data to a JSON File in Python - sqlpey
November 24, 2024 - Appending entries to a JSON file can sometimes feel challenging due to the nature of JSON structures. If you’re attempting to create a function that adds new entries to a JSON file without overwriting the existing data, you’re not alone. Below is an exploration of how to achieve this, along with alternative methods for data storage. The objective is to build a Python function that allows you to append new entries, like so:
🌐
PythonAnywhere
pythonanywhere.com › forums › topic › 12985
appending to json file : Forums : PythonAnywhere
June 29, 2018 - def write_json(data, filename='answer.json'): with open(filename,'w') as f: json.dump(data, f, indent=2, ensure_ascii=False) with this code, I created the file answer.txt, which appears in my default directory (directory after home) The problem is, that I want to append to existing json file another json data.
🌐
Stack Overflow
stackoverflow.com › questions › 71505538 › how-to-append-data-to-json-file-in-python
How to append data to json file in python? - Stack Overflow
Python does the right thing as data is a string, not a dictionary. Try: Copydata = json.loads(message.payload.decode('utf-8')) ... Sign up to request clarification or add additional context in comments.
🌐
PyTutorial
pytutorial.com › how-to-append-objects-to-json-in-python
PyTutorial | How to Append Objects to JSON in Python
November 6, 2024 - When working with large JSON files, it's important to consider memory efficiency. Here's a method to append objects to large JSON files without loading the entire file into memory.