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
105

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 3, 2025 - import json x = '{ "organization":"GeeksForGeeks","city":"Noida","country":"India"}' # python object to be appended y = {"pin":110096} # parsing JSON string: z = json.loads(x) # appending the data z.update(y) # the result is a JSON string: print(json.dumps(z)) ... The write_json() function reads the existing data, updates it, and then writes the updated data back to the file.
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
Unable to append data to Json array object with desired output
I’m tried getting help for same issue on stack-overflow but got no help or replies. I’m re-posting here with the hope that someone can please guide me as I’m unable to push the code to repository due to delay. My code import json import re from http.client import responses import vt import ... More on discuss.python.org
🌐 discuss.python.org
0
0
January 18, 2023
appending to json file : Forums : PythonAnywhere
If you append to .json file, most likely it will not parse as JSON anymore. Instead you need to read/parse it, then make changes to it's object representation as dicts/lists, then serialize back to string and (over)write the whole file. Read more... deleted-user-1008863 | 36 posts | July 3, 2018, 12:18 a.m. | permalink · That's an excellent point. giles | 12916 posts | PythonAnywhere ... More on pythonanywhere.com
🌐 pythonanywhere.com
September 29, 2020
Json.dump does not append my data correctly
Separate, unrelated calls to json.dump won’t “combine” anything if you append to an existing file. You will need to read in the old JSON data, and append the new data in whatever way is appropriate in Python (e.g. in a list or something), then overwrite the old data file with a new call ... More on discuss.python.org
🌐 discuss.python.org
0
0
February 14, 2024
🌐
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 requestsimpor…
🌐
CodeSpeedy
codespeedy.com › home › append to json file in python
Append to JSON file in Python - CodeSpeedy
July 3, 2020 - This tutorial will show you how to append to JSON file in Python using simple program. This program uses loads(), dumps(), update() methods.
🌐
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   June 11, 2023
🌐
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   July 11, 2023
Find elsewhere
🌐
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 - Problem Formulation Given a JSON object stored in a file named "your_file.json" such as a list of dictionaries. 💬 How to append data such as a new dictionary to it? # File "your_file.json" (BEFORE) [{"alice": 24, "bob": 27}] # New entry: {"carl": 33} # File "your_file.json" (AFTER) [{"alice": 24, "bob": 27}, {"carl": 33}] Method 1: ... Read more
🌐
Python.org
discuss.python.org › python help
Unable to append data to Json array object with desired output - Python Help - Discussions on Python.org
January 18, 2023 - I’m tried getting help for same issue on stack-overflow but got no help or replies. I’m re-posting here with the hope that someone can please guide me as I’m unable to push the code to repository due to delay. My code import json import re from http.client import responses import vt import requests with open('/home/asad/Downloads/ssh-log-parser/ok.txt', 'r') as file: file = file.read() pattern = re.compile(r'\\d{1,3}.\\d{1,3}.\\d{1,3}.\\d{1,3}') ips = pattern.findall(file) unique_ips = lis...
🌐
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.
🌐
Python Forum
python-forum.io › thread-26790.html
Append JSON's and write to file
May 13, 2020 - I have a Sample JSON record in a file as below { 'name':'John', 'age':30, 'car':'BMW' } I want to create more JSON records out of it and i want to minimize the i/o by not writing to the file system everytime i create sample record, the code below is...
🌐
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
1 month ago - This tutorial demonstrates the use of Python dictionary and list to append data to a JSON file using Python.
🌐
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
And then you insert your dictionary into that Python dictionary. And then you write that Python dictionary back into the JSON file. To convert between JSON strings and Python dictionaries, you can use the Python package “json”. ... Use json. load() , dict. update() , and json. dump() append to a JSON file
🌐
PythonAnywhere
pythonanywhere.com › forums › topic › 12985
appending to json file : Forums : PythonAnywhere
September 29, 2020 - If you append to .json file, most likely it will not parse as JSON anymore. Instead you need to read/parse it, then make changes to it's object representation as dicts/lists, then serialize back to string and (over)write the whole file. Read more... deleted-user-1008863 | 36 posts | July 3, ...
🌐
Python.org
discuss.python.org › python help
Json.dump does not append my data correctly - Python Help - Discussions on Python.org
February 14, 2024 - Separate, unrelated calls to json.dump won’t “combine” anything if you append to an existing file. You will need to read in the old JSON data, and append the new data in whatever way is appropriate in Python (e.g. in a list or something), then overwrite the old data file with a new call ...
🌐
Medium
kendhia.medium.com › appending-a-json-item-to-a-json-list-cf3cf056481a
Appending a JSON item to a JSON list | by Dhia Kennouche | Medium
January 25, 2019 - I started recently working on a Python project, I loved the language. But as a person coming from Java World, the uncertainty (I call it like this) in the use of variables and sometimes the ambiguity in its errors is killing me. Of course probably this is happening ‘cuz I’m still a newbie in this beautiful world. Now to go to our point. I needed to open a file that contains a JSON List , and append ...
🌐
EyeHunts
tutorial.eyehunts.com › home › append to json file python
Append to JSON file Python - Tutorial - By EyeHunts
January 18, 2023 - import json def write_json(new_data, filename='data.json'): with open(filename, 'r+') as file: file_data = list(json.load(file)) file_data.append(new_data) # file_data["emp_details"].append(new_data) file.seek(0) json.dump(file_data, file, indent=4) z = {'pin': 11001} write_json(z) ... import json data = '{ "ORG":"EyeHunts","city":"BLR","C":"India"}' # python object to be appended add = {"pin": 56001} # parsing JSON string: res = json.loads(data) # appending the data res.update(add) # the result is a JSON string: print(json.dumps(res))
Top answer
1 of 4
33

You can use json to dump the dicts, one per line. Now each line is a single json dict that you've written. You loose the outer list, but you can add records with a simple append to the existing file.

import json
import os

def append_record(record):
    with open('my_file', 'a') as f:
        json.dump(record, f)
        f.write(os.linesep)

# demonstrate a program writing multiple records
for i in range(10):
    my_dict = {'number':i}
    append_record(my_dict)

The list can be assembled later

with open('my_file') as f:
    my_list = [json.loads(line) for line in f]

The file looks like

{"number": 0}
{"number": 1}
{"number": 2}
{"number": 3}
{"number": 4}
{"number": 5}
{"number": 6}
{"number": 7}
{"number": 8}
{"number": 9}
2 of 4
9

If it is required to keep the file being valid json, it can be done as follows:

import json

with open (filepath, mode="r+") as file:
    file.seek(0,2)
    position = file.tell() -1
    file.seek(position)
    file.write( ",{}]".format(json.dumps(dictionary)) )

This opens the file for both reading and writing. Then, it goes to the end of the file (zero bytes from the end) to find out the file end's position (relatively to the beginning of the file) and goes last one byte back, which in a json file is expected to represent character ]. In the end, it appends a new dictionary to the structure, overriding the last character of the file and keeping it to be valid json. It does not read the file into the memory. Tested with both ANSI and utf-8 encoded files in Python 3.4.3 with small and huge (5 GB) dummy files.

A variation, if you also have os module imported:

import os, json

with open (filepath, mode="r+") as file:
    file.seek(os.stat(filepath).st_size -1)
    file.write( ",{}]".format(json.dumps(dictionary)) )

It defines the byte length of the file to go to the position of one byte less (as in the previous example).