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
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)
🌐
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

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
August 4, 2018
iCalendar files
I recommend vObject . It has some documentation and a few examples . import vobject from datetime import datetime, timedelta # Create a basic calendar event event = vobject.newFromBehaviour('vevent') event.add('dtstart').value = datetime.now() event.add('duration').value = timedelta(minutes=5) event.add('summary').value = u"Browse Reddit" event.add('description').value = u"Suggest iCalendar package for Python" event.add('url').value = "http://www.reddit.com/r/Python/comments/s7xij/icalendar_files/" # Create the calendar itself ical = vobject.Calendar() ical.add('x-wr-calname').value = u"My Calendar" ical.add('x-wr-caldesc').value = u"What I do from day to day" # Add the event to our calendar ical.add(event) # Write the calendar to disk with open('example.ics', 'w') as fh: fh.write(ical.serialize()) I used it to create BBC schedule calendars from JSON data. More on reddit.com
🌐 r/Python
8
5
April 4, 2012
How To Combine Two Json Values
You can accomplish this with jq like so: $ jq -r '"\(.ip):\(.ports[] | .port)"' <<-EOF { "ip": "127.0.0.1", "timestamp": "1565343832", "ports": [ {"port": 80, "proto": "tcp", "status": "open", "reason": "syn-ack", "ttl": 245} ] } { "ip": "127.0.0.2", "timestamp": "1565343837", "ports": [ {"port": 81, "proto": "tcp", "status": "open", "reason": "syn-ack", "ttl": 43} ] } EOF 127.0.0.1:80 127.0.0.2:81 Or, from a file: $ jq -r '"\(.ip):\(.ports[] | .port)"' «filename» 127.0.0.1:80 127.0.0.2:81 ⋮ ** Explanation -r means raw-output, that is, it outputs JSON strings as themselves so that the JSON string "hello, world" is output as hello, world instead of as "hello, world". That is, without the quotation marks. the single quotes protect the jq program from being interpreted by the shell (presumably bash). the filter itself is a JSON string in double quotes. It means, "for every input, output this string". So jq -r '"foo"' «filename» would output foo for every JSON value in the file. inside a string filter, you can specify substitutions (like %s in a printf). They take the form \(…) (backslash open paren … close paren). The part inside the parens is a jq expression to be substituted. .ip means output the value of the field with key "ip" in the current JSON object. the .ports [] | .port is trickier: .ports evaluates to the field with key "ports", which is the JSON array [{"port": … }]. the [] is a jq operator that says "for every JSON array I get as input, output one JSON value for element of the array". the | is kind of like a bash "pipe"—it indicates that you are passing JSON outputs from the left side to the jq expression on the right side. the .port on the right evaluates to the value of the field with key "port" If the "ports" array had more than one value, then the whole string would be output once for each value in that array. For example, if your file had an entry like {"ip":"127.0.0.1","timestamp":"1565343832","ports":[ {"port":80,"proto":"tcp","status":"open","reason":"syn-ack","ttl":245}, {"port":8000,"proto":"udp"} ]} It would generate output like: 127.0.0.1:80 127.0.0.1:8000 More on reddit.com
🌐 r/bash
14
12
June 13, 2019
AWS Lambda to JSON Object in S3 Bucket?

That should be an easy one! Set the Lambda function to be triggered by kinesis. In the lambda, use the AWS SDK to write to S3. Make sure the Lambda has the right role.

More on reddit.com
🌐 r/aws
4
4
March 9, 2015
🌐
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: ... indentation · After converting the dictionary to a JSON object, simply write it to a file using the "write" function....
Published   August 5, 2025
🌐
W3Schools
w3schools.com › python › python_json.asp
Python JSON
JSON is text, written with JavaScript object notation. Python has a built-in package called json, which can be used to work with JSON data.
🌐
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.
🌐
Quora
quora.com › How-do-you-create-a-JSON-payload-in-Python
How to create a JSON payload in Python - Quora
Answer: create the data you want as Python dictionaries and lists (remembering that json dictionaries can only have strings as keys), and then use the json [1] module to encode the Python data as a json payload.
Find elsewhere
🌐
DataCamp
datacamp.com › tutorial › json-data-python
Python JSON Data: A Guide With Examples | DataCamp
December 3, 2024 - Configuration Files. JSON provides a simple and easy-to-read format for storing and retrieving configuration data. This can include settings for the application, such as the layout of a user interface or user preferences. IoT (Internet of Things). IoT devices often generate large amounts of data, which can be stored and transmitted between sensors and other devices more efficiently using JSON. python_obj = { "name": "John Doe", "age": 30, "email": "john.doe@example.com", "is_employee": True, "hobbies": [ "reading", "playing soccer", "traveling" ], "address": { "street": "123 Main Street", "city": "New York", "state": "NY", "zip": "10001" } } print(python_obj)
🌐
Python documentation
docs.python.org › 3 › tutorial › inputoutput.html
7. Input and Output — Python 3.14.3 documentation
Rather than having users constantly writing and debugging code to save complicated data types to files, Python allows you to use the popular data interchange format called JSON (JavaScript Object Notation). The standard module called json can take Python data hierarchies, and convert them to string representations; this process is called serializing.
🌐
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.
🌐
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 - To store JSON data in a file, you can use the `json` module, which is part of the Python standard library.
🌐
freeCodeCamp
freecodecamp.org › news › how-to-use-the-json-module-in-python
How to Use the JSON Module in Python – A Beginner's Guide
June 5, 2023 - The JSON module provides you with a json.dumps() function to serialize Python objects into a JSON formatted string. It provides various options for customization, including formatting the output to make it more human-readable.
🌐
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.
🌐
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.
🌐
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 - Writing JSON to a file in Python is a simple and effective way to store data. By using the `json` module, you can easily convert Python dictionaries to JSON format and save them for later use.
🌐
HackerNoon
hackernoon.com › how-to-read-and-write-json-files-in-python
How to read and write JSON files in Python | HackerNoon
March 19, 2024 - We will discuss how to use Python to read, write, and manipulate JSON files.
🌐
LearnPython.com
learnpython.com › blog › json-in-python
How to Convert a String to JSON in Python | LearnPython.com
This creates a file called new_employee.json in your current working directory and opens it in write mode. Then, we use the dump() method to serialize a Python dictionary.
🌐
Visual Studio Code
code.visualstudio.com › docs › python › debugging
Python debugging in VS Code
November 3, 2021 - Select the create a launch.json file link (outlined in the image above) or use the Run > Open configurations menu command. Select Python Debugger from the debugger options list.
🌐
GeeksforGeeks
geeksforgeeks.org › python › json-dump-in-python
json.dump() in Python - GeeksforGeeks
January 13, 2026 - The json.dump() function in Python is used to convert (serialize) a Python object into JSON format and write it directly to a file.
🌐
JSON
json.org
JSON
It is based on a subset of the JavaScript Programming Language Standard ECMA-262 3rd Edition - December 1999. JSON is a text format that is completely language independent but uses conventions that are familiar to programmers of the C-family of languages, including C, C++, C#, Java, JavaScript, Perl, Python, and many others.