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

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
Add values to JSON object in Python - Stack Overflow
I'm trying to use the json library in python to load the data and then add fields to the objects in the "accidents" array. More on stackoverflow.com
๐ŸŒ stackoverflow.com
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
5
0
January 18, 2023
Append element into a json object python - Stack Overflow
I have a Json object and Im trying to add a new element every time I enter a new number. The Json looks like this: ... import json number = raw_input("enter a number: ") json_file = 'json.json' json_data = open(json_file) data = json.load(json_data) data.append({"range": number}) print data ยท If my new number is 10 for example... More on stackoverflow.com
๐ŸŒ stackoverflow.com
September 16, 2015
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)
๐ŸŒ
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
Find elsewhere
๐ŸŒ
CopyProgramming
copyprogramming.com โ€บ howto โ€บ how-to-add-element-in-json
Python: Adding elements to a JSON: A Guide
March 19, 2023 - Adding element to Json list (Python), 1) To reference the list, use data ['test'] -- data ['test'] [0] is the first 't' in 'test 1'. 2) To overwrite the output file, you need to close the file first and reopen โ€ฆ
๐ŸŒ
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 โ€ฆ
๐ŸŒ
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.
๐ŸŒ
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.
๐ŸŒ
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 focuses on appending new data to a JSON file in Python programming. import json # Open the JSON file for reading with open('data.json', 'r') as file: data = json.load(file) # Add a new element to the JSON data data['new_key'] = 'new_value' # Write the updated data back ...
๐ŸŒ
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 ...
๐ŸŒ
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.
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.

๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ how to append an dictionary into a json file?
r/learnpython on Reddit: How to append an dictionary into a json file?
September 2, 2023 -

Hello I currently learning json in python i want to append a dictionary in a json file ontop of existing ones but every time i do this i get this error in VS-Code:

End of file expected.

Can somebody help me?

Here is the Code:

dict = {
    "data1" : data3,
       
    "data2" : data4        
}
    
data = json.dumps(dict)
with open("index.json" , "a") as file:
    
    json.dump(data , file)