import json
with open('result.json', 'w') as fp:
    json.dump(sample, fp)

This is an easier way to do it.

In the second line of code the file result.json gets created and opened as the variable fp.

In the third line your dict sample gets written into the result.json!

Answer from moobi on Stack Overflow
🌐
Python
docs.python.org › 3 › library › json.html
JSON encoder and decoder — Python 3.14.3 documentation
1 month ago - Serialize obj to a JSON formatted str using this conversion table. The arguments have the same meaning as in dump(). ... Keys in key/value pairs of JSON are always of the type str.
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
python - How to write a new dictionary to a json file - Stack Overflow
If you want a list of dicts, then use that structure in Python, the procedure is still the same for updating the file. ... You're implicitly assuming that the file will be closed here. That is true on CPython, but not on all Python implementations. A better approach would be: with open('somefile.json... More on stackoverflow.com
🌐 stackoverflow.com
JSON and Dictionary
The core of your answer is correct: JSON is some string representation of data dicts are objects in memory But your explanations are geting away from these facts. 1. Comparing notation dicts are not strings! You say that dicts are represented by "curly braces" . So you are comparing json with dict representation, not dicts themselves. my_dict = dict('name' = 'eagle221b', 'platform' = 'reddit') This is another representation of dicts, that does not look like JSOn at all. Also you are saying "curly braces"in JSON are objects. No they are representations of objects. This makes a great difference when working with them. 2. the power of dicts So let me create another example again: my_list = [] my_dict1 = {'my_list': my_list} my_dict2 = {'my_list': my_list} my_list.append('foo') The last command has not changed any of the dicts, but if you print them, you will see the representation has changed. Also about the values: you can store objects or even functions in them. A value in dicts is just a memory pointer. (and yes, any number in python is an object) Conclusion They both are completly different things that both are based on a key value principle. But one is a text, one is memory and therefore very different. More on reddit.com
🌐 r/Python
49
250
October 10, 2020
Save dict{} to a file that can actually be opened and read by a human, but also retrieved as a dict in my code.
Look into the json module maybe? More on reddit.com
🌐 r/learnpython
9
4
October 21, 2022
🌐
GeeksforGeeks
geeksforgeeks.org › python › how-to-convert-python-dictionary-to-json
How To Convert Python Dictionary To JSON? - GeeksforGeeks
July 12, 2025 - Note: For more information, refer to Read, Write, and Parse JSON using Python ... json.dump() writes a dictionary directly into a file in JSON format. It avoids the need to manually open and write the JSON string to a file.
🌐
KDnuggets
kdnuggets.com › convert-python-dict-to-json-a-tutorial-for-beginners
Convert Python Dict to JSON: A Tutorial for Beginners - KDnuggets
So each book record is in a Python dictionary with the following keys: title, author, publication_year, and genre. When calling json.dumps(), we set the optional indent parameter—the indentation in the JSON string as it helps improve readability (yes, pretty printing json we are ??):
🌐
TutorialsPoint
tutorialspoint.com › How-to-print-Python-dictionary-into-JSON-format
How to print Python dictionary into JSON format?
We can use it to return the dictionary contents in JSON format by using the json.dumps() function inside it. In this example, we will use the __str__(self) method to return the python Dictionary into JSON format -
🌐
Oregon State University
blogs.oregonstate.edu › logicbot › 2022 › 04 › 08 › saving-a-dictionary-with-json
Saving a dictionary with JSON – Logic_bot
This is where json.dumps() function comes in. You can see below that I declared and example dictionary and then converted the dictionary by passing it to json.dumps() If you print it out at this point you will see that the file has been changed into the JSON format.
Find elsewhere
🌐
Spark By {Examples}
sparkbyexamples.com › home › python › convert python dictionary to json
Convert Python Dictionary to JSON - Spark By {Examples}
May 31, 2024 - This can be any Python object that is JSON serializable, such as a dictionary or a list. Alternatively, you can also put this data to a file and read json from a file into a object. Following is the syntax of writing JSON data to file. # Syntax of write JSON data to file import json with open("data.json", "w") as outfile: # json_data refers to the above JSON json.dump(json_data, outfile)
🌐
Edureka Community
edureka.co › home › community › categories › python › is it possible to save python dictionary into...
Is it possible to save python dictionary into json files | Edureka Community
September 4, 2019 - 56319/is-it-possible-to-save-python-dictionary-into-json-files ... Is it possible to save python dictionary into... Reading different format files from s3 having decoding issues using boto3 May 17, 2024
🌐
Scaler
scaler.com › home › topics › convert dictionary to json python
Convert Dictionary to JSON Python - Scaler Topics
April 21, 2024 - In the below article, we shall be understanding how we can make use of json.dumps() function by utilizing its various parameters to convert the dict to json python.
🌐
Sentry
sentry.io › sentry answers › python › write json data to a file in python
Write JSON data to a file in Python | Sentry
We can do this using Python’s built-in json library and file operations. Specifically, the json.dump function allows us to serialize a Python dictionary as JSON for writing to disk.
🌐
PythonForBeginners.com
pythonforbeginners.com › home › convert dictionary to json in python
Convert Dictionary to JSON in Python - PythonForBeginners.com
February 2, 2023 - Then, we used the dump() method to write the dictionary to the json file. Finally, we closed the file using the close() method. If the python dictionary contains elements other than the primitive data types and container objects such as lists, the above approaches won’t work.
🌐
Analytics Vidhya
analyticsvidhya.com › home › how to convert python dictionary to json?
How To Convert Python Dictionary To JSON? - Analytics Vidhya
January 11, 2024 - Customize the JSON output’s format by utilizing the indent parameter in json.dumps(). Adjust the number of spaces for indentation to enhance readability. For large dictionaries or frequent conversions, consider leveraging third-party libraries like simplejson, ujson, or rapidjson for improved performance. While converting Python dictionaries to JSON, be mindful of common issues:
🌐
Board Infinity
boardinfinity.com › blog › dict-to-json-in-python
Dictionary to JSON: Conversion in Python | Board Infinity
January 2, 2025 - JSON files are normally used to store persistent data. To write dictionaries to JSON files in Python use json.dump().
Top answer
1 of 1
6

There are a few issues here:

file = open('somefile.json', 'a',encoding="utf-8")

You're implicitly assuming that the file will be closed here. That is true on CPython, but not on all Python implementations. A better approach would be:

with open('somefile.json', 'a',encoding="utf-8") as file:
    file.write(json_obj)

Because that uses a context manager to explicitly close the file.

Second, you can avoid creating an extra string by writing directly to the file:

with open('somefile.json', 'a',encoding="utf-8") as file:
    json.dump(someDict, file)

Third, having multiple JSON objects in a file is not valid JSON. There are a few approaches you could take here. One is to wrap the JSON objects in a list:

[
{
    "a": 1,
    "b":2,
    "c": 3
},
{
    "a1": 1,
    "b1":2,
    "c1": 3
}
]

So, start the file with an open bracket, and write a comma after every JSON object, except the last one, then end the file with a close bracket.

Second approach would be to newline-separate your JSON objects, like this:

{"a": 1,"b":2,"c": 3}
{"a1": 1, "b1":2,"c1": 3}

Each line is a JSON object. You'd read this like so:

with open("filename", "rt") as file:
    for line in file:
        obj = json.loads(line)
        # do something with obj
        # ...

The advantage of this approach would be that you can now load each individual JSON object in memory, without having to load the entire file in at once. The disadvantage is that you're no longer writing valid JSON, so you can't use tools like jq on the output. (If you want the best of both worlds, you can use a package like ijson, but that's more complex.)

🌐
FavTutor
favtutor.com › blogs › dict-to-json-python
5 Ways to Convert Dictionary to JSON in Python | FavTutor
October 5, 2021 - Learn how to convert dict to json in python along with a brief introduction about dictionary and json in 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
... Appending a dictionary to a JSON file can mean two things: adding the dict as an element in a JSON array stored in the file, or writing successive JSON objects newline-delimited (NDJSON).
🌐
Leapcell
leapcell.io › blog › how-to-convert-a-python-dictionary-to-json
How to Convert a Python Dictionary to JSON | Leapcell
July 25, 2025 - Use json.dumps() to convert a Python dictionary into a JSON-formatted string. Use json.dump() to write JSON data directly to a file.
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-convert-list-of-dictionaries-to-json
Python - Convert list of dictionaries to JSON - GeeksforGeeks
July 5, 2025 - json.dump() saves the list of dictionaries to output.json, converting tuples to lists using the default parameter. indent=2 formats the JSON neatly, and a confirmation message is printed after saving.
🌐
Quora
quora.com › How-do-I-write-multiple-Python-dictionaries-to-a-JSON-file
How to write multiple Python dictionaries to a JSON file - Quora
First load the json file with an empty Dict. with open(‘file.json', ‘w') as f: json.loads(“{}”,f) Then write the Dict and store the data. Open the json file in read mode. with open(‘file.json', ‘r') as r: Data = hain.dumps(r) ...