You can do this.

data[0]['f'] = var
Answer from Jayanth Koushik on Stack Overflow
๐ŸŒ
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)

Top answer
1 of 3
6

There are several questions here. The main points worth mentioning:

  • Use can use a list to hold your arguments and use *args to unpack when you supply them to add_entry.
  • To check / avoid duplicates, you can use set to track items already added.
  • For writing to JSON, now you have a list, you can simply iterate your list and write in one function at the end.

Putting these aspects together:

import json

res = []
seen = set()

def add_entry(res, name, element, type):

    # check if in seen set
    if (name, element, type) in seen:
        return res

    # add to seen set
    seen.add(tuple([name, element, type]))

    # append to results list
    res.append({'name': name, 'element': element, 'type': type})

    return res

args = ['xyz', '4444', 'test2']

res = add_entry(res, *args)  # add entry - SUCCESS
res = add_entry(res, *args)  # try to add again - FAIL

args2 = ['wxy', '3241', 'test3']

res = add_entry(res, *args2)  # add another - SUCCESS

Result:

print(res)

[{'name': 'xyz', 'element': '4444', 'type': 'test2'},
 {'name': 'wxy', 'element': '3241', 'type': 'test3'}]

Writing to JSON via a function:

def write_to_json(lst, fn):
    with open(fn, 'a', encoding='utf-8') as file:
        for item in lst:
            x = json.dumps(item, indent=4)
            file.write(x + '\n')

#export to JSON
write_to_json(res, 'elements.json')
2 of 3
1

you can try this way

import json
import hashlib


def add_entry(name, element, type):
        return {hashlib.md5(name+element+type).hexdigest(): {"name": name, "element": element, "type": type}}


#add entry
entry = add_entry('xyz', '4444', 'test2')


#Update to JSON
with open('my_file.json', 'r') as f:
    json_data = json.load(f)
    print json_data.values() # View Previous entries
    json_data.update(entry)

with open('elements.json', 'w') as f:
    f.write(json.dumps(json_data))
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ append-to-json-file-using-python
Append to JSON file using Python - GeeksforGeeks
July 1, 2026 - Explanation: json.loads() function converts the JSON string into a Python dictionary. The update() method adds the new key-value pair, and json.dumps() converts the updated dictionary back into a JSON string.
Find elsewhere
๐ŸŒ
Medium
anjugopinath.medium.com โ€บ appending-to-a-dictionary-e48b6d701324
Appending to a dictionary in python | by Anju Gopinath | Medium
June 11, 2023 - Python ยท Dictionary ยท Json ยท ...json_object) Add entries to the dictionary with โ€œupdateโ€ : import json filename = 'sample.json' entry = {'orange': 2} # 1....
๐ŸŒ
Devgex
devgex.com โ€บ en โ€บ article โ€บ 00020275
Complete Guide to Adding Elements to JSON Files in Python - DevGex
November 23, 2025 - This method accesses the first dictionary element in the list via indexing and then uses dictionary assignment syntax to add the new key-value pair. After execution, the data becomes: [{'a': 'A', 'b': (2, 4), 'c': 3.0, 'f': 2.4}], fully meeting the user's expectations. Let's demonstrate this process with a complete code example: import json # Initial data original_data = [{'a': 'A', 'b': (2, 4), 'c': 3.0}] print('Original data:', repr(original_data)) # New value to add new_value = 2.4 # Correct method to add element original_data[0]['f'] = new_value print('Modified data:', repr(original_data)) # Convert to JSON string json_output = json.dumps(original_data) print('JSON output:', json_output)
๐ŸŒ
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...
๐ŸŒ
SitePoint
sitepoint.com โ€บ python, perl and golang โ€บ python
Adding a new key to a nested dictionary in python - Python - SitePoint Forums | Web Development & Design Community
December 21, 2016 - JSON: {'result':[{'key1':'valu... list, like this: dict = {'result':[{'key1':'value1','key2':'value2'}, {'key1':'value3','key2':'value4'}]} length = len(dict['result']) print(length) data_dict[......
๐ŸŒ
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...
๐ŸŒ
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
๐ŸŒ
W3Schools
w3schools.com โ€บ python โ€บ python_dictionaries_add.asp
Python - Add Dictionary Items
Python Dictionaries Access Items Change Items Add Items Remove Items Loop Dictionaries Copy Dictionaries Nested Dictionaries Dictionary Methods Dictionary Exercises Code Challenge Python If...Else