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"
      }
    }
  }
}
Answer from Anna Nevison on Stack Overflow
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
3

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)
🌐
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".
Discussions

python - How do I write JSON data to a file? - Stack Overflow
How do I write JSON data stored in the dictionary data to a file? ... For flags when opening file: Here, we used "w" letter in our argument, which indicates write and will create a file if it does not exist in library Plus sign indicates both read and write, guru99.com/reading-and-writing-files-in-python... More on stackoverflow.com
🌐 stackoverflow.com
How to create a json file in python? - Stack Overflow
I want to convert these fields into JSON format and store it in a JSON file. I cannot convert the tags into a single dictionary, because the key cannot hold many values. So, I want to convert these fields directly into JSON? How to create a properly managed json data format from these fields? More on stackoverflow.com
🌐 stackoverflow.com
How would you use python to create JSON files?
From StackOverflow JSON is basically a way of communicating data to someone, with very specific rules. Using Key Value Pairs and Arrays. JSON is very lightweight and is a nice way to store information. If you request a web-server, most responses will be in JSON format. Example of JSON data (also from StackOverflow): { "first_name": "John", "last_name": "Smith", "address": { "street_address": "21 2nd Street", "city": "New York", "state": "NY", "postal_code": 10021 }, "phone_numbers": [ "212 555-1234", "646 555-4567" ] } Now, to answer your question. How to create JSON files using Python? First, you need valid JSON in your Python code. images = [ { "name": "awesome_image.png", "file_size": 1240000, "file_type": "image/png", }, { "name": "good_image.jpg", "file_size": 742600, "file_type": "image/jpeg" } ] Now, using the json library # Load data. This will transform the data into an indented string. json_data = json.dumps(images, indent=2) # Create and write to file. with open("/home/user/Documents/images.json", "w") as json_file: json_file.write(json_data) How to load JSON files in Python? # Open file in read mode. with open("/home/user/Documents/images.json", "r") as f: # We can do this in two ways. # 1. Load file directly. data = json.load(f) # 2. Load from the file's contents. data = json.loads(f.read()) Now all the file content is stored in the data variable. If you are dealing with files, it's better to load and work with them in Python. It'll be faster than to keep opening and closing files all the time. Create functions to write/load files and use them when you need to. More on reddit.com
🌐 r/learnpython
7
5
March 7, 2020
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
June 15, 2019
🌐
YouTube
youtube.com › watch
How to Create a JSON file in Python (Python and JSON Tutorial 03) - YouTube
In this video, we work with the same data as before and we explore how to create a json file. This is an easy tutorial.If you enjoy this video, please subscr...
Published: April 7, 2020
🌐
Srinimf
srinimf.com › 2021 › 11 › 12 › how-to-create-json-file-in-python
How to Create a JSON File in Python: Step-by-Step Guide for Beginners – Srinimf
October 12, 2025 - Opening the File with open('data.json', 'w', encoding='utf-8') as f: ... Do import JSON, which is the first step that pulls the JSON package into the program. So we can use all the available JSON methods.
🌐
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 - 💬 Question: How would we write code to create and work with a JSON File? ... This example creates an empty JSON file if one does not exist in the current working directory. import os filename = 'employees.json' isFile = os.path.isfile(filename) if (not isFile): with open(filename, 'w') as fp: pass else: print(f'The {filename} file exists.') The first line in the above code snippet imports Python’s built-in os library.
🌐
CodeSignal
codesignal.com › learn › courses › hierarchical-and-structured-data-formats › lessons › constructing-objects-and-writing-to-json-files
Constructing Objects and Writing to JSON Files
Ensure data types in Python are compatible with JSON (e.g., dictionaries and lists). Always close files to avoid resource leaks; the with statement is a helpful tool here. Use indent to create human-readable JSON files—this can be useful for debugging and manual inspection.
🌐
Medium
medium.com › @mary.paskhaver › make-a-json-file-in-python-943a71b7cf4f
Make a JSON File in Python. Learn how to write data to a JSON file | by Mary Paskhaver | Medium
August 16, 2023 - If not, check out the beginning of this article to set up your computer for Python development. You can use the open function to create your file. You should give it these arguments: The path we want our JSON file to have.
Find elsewhere
🌐
GeeksforGeeks
geeksforgeeks.org › python › build-a-json-object-in-python
Build a Json Object in Python - GeeksforGeeks
July 23, 2025 - A Python dictionary named 'data' is used to store the object in key-value pairs. json.dumps( ) is used convert the Python dictionary into JSON formatted string and result is displayed.
🌐
LearnPython.com
learnpython.com › blog › json-in-python
How to Convert a String to JSON in Python | LearnPython.com
The first one is the object that stores the data to be serialized (here, a Python dictionary). The second one is the file to write the serialized data. The indent parameter is optional. The tool() method of the json library allows for pretty-printing JSON files in the command line. Let’s try it on the new_employee.json file we created in the previous section.
Top answer
1 of 16
3357

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.

🌐
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: ... the number of units for indentation · After converting the dictionary to a JSON object, simply write it to a file using the "write" function....
Published: August 5, 2025
🌐
Board Infinity
boardinfinity.com › blog › json-file-in-python
JSON file in Python: Read and Write | Board Infinity
January 3, 2025 - Often when dealing with large amounts of JSON data you might wish to add white space in order to make diagnostics or logs more readable. The json.dumps() function is used for pretty formatting of JSON data instead of writing it in a file. ... #pretty write json file in python import json # Sample Python dictionary data = { "name": "John", "age": 30, "isStudent": False, "courses": ["Math", "Science"] } # Convert Python dictionary to JSON string with pretty formatting json_string = json.dumps(data, indent=4) # Print the formatted JSON string print(json_string)
🌐
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.
🌐
Better Stack
betterstack.com › community › questions › how-to-write-json-data-to-file-in-python
How do I write JSON data to a file in Python? | Better Stack Community
You can use the json module in Python to write JSON data to a file. The module has a dump() function that can be used to write JSON data to a file-like object.
🌐
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.
🌐
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
🌐
Code Institute
codeinstitute.net › blog › python › working with json in python: a beginner’s guide
Working with JSON in Python: A Beginner's Guide - Code Institute DE
February 6, 2024 - This is particularly useful when you need to save the state of your program or share data with other applications. To store JSON data in a file, you can use the `json` module, which is part of the Python standard library.
🌐
YouTube
youtube.com › bro code
WRITE FILES using Python! (.txt, .json, .csv) ✍ - YouTube
00:00:00 .txt00:03:06 absolute file path00:04:09 mode="x"00:05:35 mode="a"00:06:31 collections00:08:15 .json00:10:30 .csv
Published: July 12, 2024
Views: 4K
🌐
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 learn about handling more complex scenarios and ...