Как создать .json-файл в Python?

How to create a .json file in Python?

I was looking through some notes on my blog (yes, yes, it’s like a cheat sheet, so yes, I’m peeping here, and not just writing), and I realized that the question is: How to create a .json file in Python? has not been described.

There is a solution to questions on reading data from .json, there is a solution to adding data to .json, there is even a description of the solution to the problem of deleting an entry from .json files. But the process of creating .json files is not described! How it happened is not clear, but today I will correct this error. So… How to create a .json file in Python?

Creating a .json file in Python comes down to writing a dictionary or list in JSON format to a file.
Here is an example of creating a .json file using the json module:

import json
 
# Creating a dictionary
data = {
"name": "John",
"age": 30,
"city": "New York"
}
 
# Writing a dictionary to a .json file
with open("data.json", "w") as json_file:
json.dump(data, json_file)

In this example, we create a data dictionary and write it to the data.json file. We use the json.dump() method, which takes a data dictionary and a json_file file object to write to.

You can also use the json.dumps() method to serialize the dictionary into a JSON string, which can then be written to a file:

import json
 
# Creating dictionary
data = {
"name": "John",
"age": 30,
"city": "New York"
}
 
# Convert dictionary to JSON string
json_string = json.dumps(data)
 
# Writing a JSON string to a .json file
with open("data.json", "w") as json_file:
json_file.write(json_string)

Here we use the json.dumps() method to convert the data dictionary into a JSON string, which is then written to a file.

Phew… it’s gotten easier 🙂 I hope there won’t be more questions related to how to create a .json file in Python. And if there are, you are welcome to the mail, or in Telegram.