You can do this.

data[0]['f'] = var
Answer from Jayanth Koushik on Stack Overflow
🌐
GeeksforGeeks
geeksforgeeks.org › python › append-to-json-file-using-python
Append to JSON file using Python - GeeksforGeeks
July 3, 2025 - Syntax: json.dumps(object) Parameter: It takes Python Object as the parameter. Return type: It returns the JSON string. Updates a dictionary with elements from another dictionary or iterable key-value pairs.
Discussions

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
python - How to add an element to a list? - Stack Overflow
If you want to add element to a specific place in a list (i.e. to the beginning), use insert() instead: >>> data['list'].insert(0, {'b':'2'}) >>> data {'list': [{'b': '2'}, {'a': '1'}]} After doing that, you can assemble JSON again from dictionary you modified: More on stackoverflow.com
🌐 stackoverflow.com
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
Add elements to a JSON file?
I am working on a transform, but I don't know the pythonic approach to solve this: if I have this array: list = [{'NestID': '1', 'Ch2': '68'}, {'NestID': '2', 'Ch2': '133'}, {'NestID': '3', 'Ch2': '65'}, {'NestID': '4', 'Ch1': '2'}] How do I modify it so I can change the 1st and 3rd element ... More on forum.inductiveautomation.com
🌐 forum.inductiveautomation.com
0
0
November 2, 2022
🌐
Medium
mae-morano-64788.medium.com › editing-deleting-and-adding-elements-to-a-json-file-using-python-5615ea6a0ace
Editing, Deleting and Adding Elements to a JSON file using Python | by Mae Morano | Medium
September 29, 2020 - Editing, Deleting and Adding Elements to a JSON file using Python How I handled Editing, Deleting and Adding Quiz Questions in a JSON file for my Simple Quiz written in Python As you remember in my …
🌐
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...
🌐
Inductive Automation
forum.inductiveautomation.com › general discussion
Add elements to a JSON file? - General Discussion - Inductive Automation Forum
November 2, 2022 - I am working on a transform, but I don't know the pythonic approach to solve this: if I have this array: list = [{'NestID': '1', 'Ch2': '68'}, {'NestID': '2', 'Ch2': '133'}, {'NestID': '3', 'Ch2': '65'}, {'NestID': '4', 'Ch1': '2'}] How do I modify it so I can change the 1st and 3rd element of this list to be like this: {'NestID': '2', 'Ch2': '133', 'Ch3': '20'} {'NestID': '4', 'Ch1': '2','Ch2': '7','Ch4': '9'}] So that my entire list changes to: [{'NestID': '1', 'Ch2': '68'}, {'Nest...
Find elsewhere
🌐
YouTube
youtube.com › watch
Python How to append a JSON object to a JSON array - YouTube
Download this code from https://codegive.com Title: How to Append a JSON Object to a JSON Array in PythonIntroduction:Appending a JSON object to a JSON array...
Published   November 26, 2023
🌐
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 - To update a JSON object in a file, import the json library, read the file with json.load(file), add the new entry to the list or dictionary data structure data, and write the updated JSON object with json.dump(data, file). In particular, here are the four specific steps to update an existing ...
🌐
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.
🌐
Baeldung
baeldung.com › home › scripting › adding field to a json object
Adding Field to a JSON Object | Baeldung on Linux
March 18, 2024 - In this article, we learned a few ways to add an attribute and an object to an existing JSON object. Firstly, we created a fairly limited Bash program that relies on sed and a regular expression. Secondly, using the jq command is perhaps the simplest and most concise way of manipulating the JSON object from the command line. Lastly, Python, Perl, and Node scripts aided our goal, but may require deeper knowledge to use and expand upon.
🌐
Reddit
reddit.com › r/learnpython › how to append a json object to the beginning of the file?
r/learnpython on Reddit: How to append a json object to the beginning of the file?
January 29, 2022 -
def write(filename, new_data):  # function that appends data to the specified file
    with open(filename, "r") as file1:
        data = json.load(file1)
        data.append(new_data)
    with open(filename, "w") as file1:
        # Sets file's current position at offset.
        file1.seek(0)
        json.dump(data, file1, indent=4)

I have this function that appends objects exactly how I want; however, it only does it to the bottom of the file rather than the top.

Top answer
1 of 2
6

First, accidents is a dictionary, and you can't write to a dictionary; you just set values in it.

So, what you want is:

for accident in accidents:
    accident['Turn'] = 'right'

The thing you want to write out is the new JSON—after you've finished modifying the data, you can dump it back to a file.

Ideally you do this by writing to a new file, then moving it over the original:

with open('sanfrancisco_crashes_cp.json') as json_file:
    json_data = json.load(json_file)
accidents = json_data['accidents']
for accident in accidents:
    accident['Turn'] = 'right'
with tempfile.NamedTemporaryFile(dir='.', delete=False) as temp_file:
    json.dump(temp_file, json_data)
os.replace(temp_file.name, 'sanfrancisco_crashes_cp.json')

But you can do it in-place if you really want to:

# notice r+, not rw, and notice that we have to keep the file open
# by moving everything into the with statement
with open('sanfrancisco_crashes_cp.json', 'r+') as json_file:
    json_data = json.load(json_file)
    accidents = json_data['accidents']
    for accident in accidents:
        accident['Turn'] = 'right'
    # And we also have to move back to the start of the file to overwrite
    json_file.seek(0, 0)
    json.dump(json_file, json_data)
    json_file.truncate()

If you're wondering why you got the specific error you did:

In Python—unlike many other languages—assignments aren't expressions, they're statements, which have to go on a line all by themselves.

But keyword arguments inside a function call have a very similar syntax. For example, see that tempfile.NamedTemporaryFile(dir='.', delete=False) in my example code above.

So, Python is trying to interpret your accident['Turn'] = 'right' as if it were a keyword argument, with the keyword accident['Turn']. But keywords can only be actual words (well, identifiers), not arbitrary expressions. So its attempt to interpret your code fails, and you get an error saying keyword can't be an expression.

2 of 2
0

I solved with that :

with open('sanfrancisco_crashes_cp.json') as json_file:
        json_data = json.load(json_file)

        accidents = json_data['accidents']
        for accident in accidents:
            accident['Turn'] = 'right'

with open('sanfrancisco_crashes_cp.json', "w") as f:
        json.dump(json_data, f)
🌐
Iditect
iditect.com › faq › python › add-element-to-a-json-file-in-python.html
Add element to a JSON file in python?
Description: This query is seeking guidance on appending new data to an existing JSON file in Python. import json # Open the JSON file for reading and appending with open('data.json', 'r+') as file: # Load existing data data = json.load(file) # Add new element data['new_key'] = 'new_value' # Set ...
🌐
IQCode
iqcode.com › code › javascript › how-to-add-items-to-an-existing-json-file-python
how to add items to an existing json file python Code Example
September 30, 2021 - a_dictionary = {"d": 4} with open("sample_file.json", "r+") as file: data = json.load(file) update(a_dictionary) seek(0) dump(data, file) ... Unlock the power of data and AI by diving into Python, ChatGPT, SQL, Power BI, and beyond.
🌐
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 a JSON object to it.
🌐
Reddit
reddit.com › r/learnpython › how do i add a nested json object to an existing object with python?
How do I add a nested JSON object to an existing object with python? : r/learnpython
November 22, 2022 - First: there's no such thing as a "JSON object". Json is just the method used to save and load data. Once it's loaded it's a standard python object.
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.