data is a Python dictionary. It needs to be encoded as JSON before writing.

Use this for maximum compatibility (Python 2 and 3):

import json
with open('data.json', 'w') as f:
    json.dump(data, f)

On a modern system (i.e. Python 3 and UTF-8 support), you can write a nicer file using:

import json
with open('data.json', 'w', encoding='utf-8') as f:
    json.dump(data, f, ensure_ascii=False, indent=4)

See json documentation.

Answer from phihag on Stack Overflow
Top answer
1 of 16
3349

data is a Python dictionary. It needs to be encoded as JSON before writing.

Use this for maximum compatibility (Python 2 and 3):

import json
with open('data.json', 'w') as f:
    json.dump(data, f)

On a modern system (i.e. Python 3 and UTF-8 support), you can write a nicer file using:

import json
with open('data.json', 'w', encoding='utf-8') as f:
    json.dump(data, f, ensure_ascii=False, indent=4)

See json documentation.

2 of 16
347

To get utf8-encoded file as opposed to ascii-encoded in the accepted answer for Python 2 use:

import io, json
with io.open('data.txt', 'w', encoding='utf-8') as f:
  f.write(json.dumps(data, ensure_ascii=False))

The code is simpler in Python 3:

import json
with open('data.txt', 'w') as f:
  json.dump(data, f, ensure_ascii=False)

On Windows, the encoding='utf-8' argument to open is still necessary.

To avoid storing an encoded copy of the data in memory (result of dumps) and to output utf8-encoded bytestrings in both Python 2 and 3, use:

import json, codecs
with open('data.txt', 'wb') as f:
    json.dump(data, codecs.getwriter('utf-8')(f), ensure_ascii=False)

The codecs.getwriter call is redundant in Python 3 but required for Python 2


Readability and size:

The use of ensure_ascii=False gives better readability and smaller size:

>>> json.dumps({'price': '€10'})
'{"price": "\\u20ac10"}'
>>> json.dumps({'price': '€10'}, ensure_ascii=False)
'{"price": "€10"}'

>>> len(json.dumps({'абвгд': 1}))
37
>>> len(json.dumps({'абвгд': 1}, ensure_ascii=False).encode('utf8'))
17

Further improve readability by adding flags indent=4, sort_keys=True (as suggested by dinos66) to arguments of dump or dumps. This way you'll get a nicely indented sorted structure in the json file at the cost of a slightly larger file size.

🌐
Real Python
realpython.com › python-json
Working With JSON Data in Python – Real Python
August 20, 2025 - With pretty_frieda.json as the value of the outfile option, you write the output into the JSON file instead of showing the content in the terminal. If the file doesn’t exist yet, then Python creates the file on the way.
Discussions

How would you use python to create JSON files?
I read two concrete questions from your post: why you would want to create a JSON object Imagine you want multiple software systems to communicate. Let's say we have three systems, one written in Python, one client written in JavaScript and one more backend system in Java. You can't just send Python objects over a network and expect the systems written in JS or Java to understand them. Same thing the other way around. In the end it's just electrical signals and both the sender and receiver need a common understanding of how to interpret those signals, otherwise they will just be gibberish. That's where data formats like JSON come into play: It's a simple and standardized data format that can be handled in any modern programming language. Now your Python code can serialize its internal representation of a piece of data into this format and send it over a network or store it on some disk, where some other system will eventually pick it up, deserialize it into its own internal representation and process it. show how you would create a JSON object with python import json data = {"year": 2020, "sales": 12345678, "currency": "€"} # creating a JSON string json_string = json.dumps(data) # storing it in a file with open("data.json", "w") as json_file: json.dump(data, json_file) More on reddit.com
🌐 r/learnpython
7
5
March 7, 2020
Generate a JSON file with Python - Stack Overflow
I'm trying to generate a JSON file with python. But I can't figure out how to append each object correctly and write all of them at once to JSON file. Could you please help me solve this? a, b, and More on stackoverflow.com
🌐 stackoverflow.com
python - How to dynamically build a JSON object? - Stack Overflow
For more beautiful and faster access to JSON response from API, take a look at this response. ... All previous answers are correct, here is one more and easy way to do it. For example, create a Dict data structure to serialize and deserialize an object · (Notice None is Null in python and I'm ... More on stackoverflow.com
🌐 stackoverflow.com
How to create a keyboard shortcut to run file in terminal?
To map, type ctrl+k, ctrl+s. Type one of the commands, right-click, choose change keybinding, enter whatever you want the binding to be. More on reddit.com
🌐 r/vscode
6
14
July 30, 2018
🌐
Replit
replit.com › home › discover › how to create a json file in python
How to create a JSON file in Python | Replit
February 12, 2026 - The json.dump() function directly serializes a Python object into a file stream. It requires two main arguments: the Python object to convert, like the data dictionary, and the file object to write to. This combines serialization and writing into one step. The with open() statement manages the file. Using "w" for write mode is a key detail. It creates the file if it doesn't exist or completely overwrites it if it does, ensuring your JSON file always reflects the latest data.
🌐
Python Examples
pythonexamples.org › python-create-json
Python Create JSON
Learn how to create JSON strings from Python dictionaries, lists, and tuples. This tutorial covers JSON creation techniques using the json.dumps() function with practical examples.
🌐
Reddit
reddit.com › r/learnpython › how would you use python to create json files?
r/learnpython on Reddit: How would you use python to create JSON files?
March 7, 2020 -

Howdy!

I recently took a coding test for an internship program, I was quickly put in check by the coding test. I am only about 50 hours into coding, but I had higher hopes for myself then how I performed.

The questions that tripped me up were how to take input in the form of a Dict [] and create a JSON object out of it. I was allowed to read documentation during the test and found the JSON library with json.dumps, but couldn't figure out how to use it in the allotted time. =^(

In the spirit of improvement would you fine folks of r/learnpython be willing to show how you would create a JSON object with python, and outline some reasons as to why you would want to create a JSON object in the first place? I'm hoping to learn something new, but I also hope that there are a few on this sub who can come across the post and learn something new too.

On the bright side, I solved FizzBuzz no problem. That problem gave me anxiety when I first started coding, and now I can solve it expertly. Little wins!

Thank you! =^)

Top answer
1 of 4
5
I read two concrete questions from your post: why you would want to create a JSON object Imagine you want multiple software systems to communicate. Let's say we have three systems, one written in Python, one client written in JavaScript and one more backend system in Java. You can't just send Python objects over a network and expect the systems written in JS or Java to understand them. Same thing the other way around. In the end it's just electrical signals and both the sender and receiver need a common understanding of how to interpret those signals, otherwise they will just be gibberish. That's where data formats like JSON come into play: It's a simple and standardized data format that can be handled in any modern programming language. Now your Python code can serialize its internal representation of a piece of data into this format and send it over a network or store it on some disk, where some other system will eventually pick it up, deserialize it into its own internal representation and process it. show how you would create a JSON object with python import json data = {"year": 2020, "sales": 12345678, "currency": "€"} # creating a JSON string json_string = json.dumps(data) # storing it in a file with open("data.json", "w") as json_file: json.dump(data, json_file)
2 of 4
3
If you know about the JSON library, there's not much more to tell. RealPython have excellent tutorials and information. https://realpython.com/python-json/ You can find a lot more by searching "python json tutorial".
🌐
Python Examples
pythonexamples.org › python-write-json-to-file
Python Write JSON to File
Prepare JSON string by converting a Python Object to JSON string using json.dumps() function. Create a JSON file using open(filename, 'w') function. We are opening file in write mode. Use file.write(text) to write JSON content prepared in step 1 to the file created in step 2. Close the JSON file.
🌐
GeeksforGeeks
geeksforgeeks.org › python › build-a-json-object-in-python
Build a Json Object in Python - GeeksforGeeks
July 23, 2025 - import json def encoder(obj): if isinstance(obj, set): return list(obj) return obj gfg = [('name', 'Hustlers'), ('age', 19), ('is_student', True)] json_data = dict(gfg) json_string = json.dumps(json_data, default=encoder) print(type(json_string)) ...
Find elsewhere
🌐
GeeksforGeeks
geeksforgeeks.org › python › reading-and-writing-json-to-a-file-in-python
Reading and Writing JSON to a File in Python - GeeksforGeeks
It takes two parameters: dictionary: ... simply write it to a file using the "write" function. Example: Convert a dictionary to a JSON string and write it to a file....
Published   August 5, 2025
🌐
LearnPython.com
learnpython.com › blog › json-in-python
How to Convert a String to JSON in Python | LearnPython.com
You can learn more about object serialization in this article. The dumps() method converts a Python object to a JSON formatted string. We can also create a JSON file from data stored in a Python dictionary.
🌐
W3Schools
w3schools.com › python › python_json.asp
Python JSON
Python has a built-in package called json, which can be used to work with JSON data. ... If you have a JSON string, you can parse it by using the json.loads() method.
🌐
Python
docs.python.org › 3 › library › json.html
JSON encoder and decoder — Python 3.14.3 documentation
4 weeks ago - Serialize obj as a JSON formatted stream to fp (a .write()-supporting file-like object) using this Python-to-JSON conversion table.
🌐
Finxter
blog.finxter.com › home › learn python blog › python create json file
Python Create JSON File – Be on the Right Side of Change
November 2, 2022 - This code snippet opens, reads the employees.json file and saves it to json_str. Upon each iteration, any additional newline (\n) characters are removed using the replace() function. Once all lines have been read, the contents of json_str is output to the terminal and is the same as indicated above. This example reads in the previously saved JSON file and accesses the ID element from each hire.
Top answer
1 of 3
7

Just use normal dictionaries in python when constructing the JSON then use the JSON package to export to JSON files.

You can construct them like this (long way):

a_dict = {}
a_dict['id'] = {}
a_dict['id']['a'] = {'properties' : {}}
a_dict['id']['a']['properties']['x'] = '9'
a_dict['id']['a']['properties']['y'] = '3'
a_dict['id']['a']['properties']['z'] = '17'
a_dict['id']['b'] = {'properties' : {}}
a_dict['id']['b']['properties']['x'] = '3'
a_dict['id']['b']['properties']['y'] = '2'
a_dict['id']['b']['properties']['z'] = '1'

or you can use a function:

def dict_construct(id, x, y, z):
 new_dic = {id : {'properties': {} } }
 values = [{'x': x}, {'y': y}, {'z':z}]
 for val in values:
    new_dic[id]['properties'].update(val)
 return new_dic

return_values = [('a', '9', '3', '17'), ('b', '3', '2', '1')]

a_dict = {'id': {} }
for xx in return_values:
    add_dict = dict_construct(*xx)
    a_dict['id'].update(add_dict)

print(a_dict)

both give you as a dictionary:

{'id': {'a': {'properties': {'x': '9', 'y': '3', 'z': '17'}}, 'b': {'properties': {'x': '3', 'y': '2', 'z': '1'}}}}

using json.dump:

with open('data.json', 'w') as outfile:
    json.dump(a_dict, outfile)

you get as a file:

{
  "id": {
    "a": {
      "properties": {
        "x": "9",
        "y": "3",
        "z": "17"
      }
    },
    "b": {
      "properties": {
        "x": "3",
        "y": "2",
        "z": "1"
      }
    }
  }
}
2 of 3
2

One way will be to create whole dict at once:

data = {} 
for i in range(1, 5):
    name = getname(i)
    x = getx(i)
    y = gety(i)
    z = getz(i)
    data[name] = {
        "x": x,
        "y": y,
        "z": z
      }

And then save

 with open('data.json', 'w') as f:
    json.dump(data, f, indent=4)
🌐
Medium
medium.com › data-science › working-with-json-data-in-python-45e25ff958ce
JSON in Python Tutorial | TDS Archive
August 11, 2021 - Writing to json files, reading from json files explained and illustrated with examples in python.
🌐
Programiz
programiz.com › python-programming › json
Python JSON: Read, Write, Parse JSON (With Examples)
Writing JSON to a file (with Example) Pretty print JSON (with Example) Previous Tutorial: Python Asserts · Next Tutorial: Python pip · Share on: Did you find this article helpful? Your builder path starts here. Builders don't just know how to code, they create solutions that matter.
🌐
iO Flood
ioflood.com › blog › python-write-json-to-file
Python Guide: How to Write JSON to a File
February 1, 2024 - We then create a dictionary with some data. Using the json.dump() function, we open a file named ‘data.json’ in write mode and write the JSON data into it. This is a basic way to write JSON to a file in Python, but there’s much more to ...
🌐
ItSolutionstuff
itsolutionstuff.com › post › python-create-json-file-from-list-exampleexample.html
Python Create JSON File from List Example - ItSolutionstuff.com
October 30, 2023 - import json # Create List for write data into json file data = ["Rajkot", "Surat", "Ahmadabad", "Baroda"] # Create Json file with list with open('data.json', 'w') as f: json.dump(data, f, indent=2) print("New data.json file is created from list") ...
🌐
Medium
medium.com › @ryan_forrester_ › writing-json-to-a-file-in-python-a-step-by-step-guide-630584957d07
Writing JSON to a File in Python: A Step-by-Step Guide | by ryan | Medium
November 6, 2024 - In Python, working with JSON is straightforward thanks to the built-in `json` module. This article will guide you through the process of writing JSON to a file in Python with detailed explanations and practical code examples, making it easy for novice learners to grasp the concept.
🌐
Simplilearn
simplilearn.com › home › resources › software development › json python: read, write, and parse json files in python
JSON Python: Read, Write, and Parse JSON Files in Python
October 11, 2022 - JSON, short for JavaScript object notation, is a syntax for storing and exchanging data. Learn how to write JSON to a file and convert from python to JSON now!
Address   5851 Legacy Circle, 6th Floor, Plano, TX 75024 United States