In this tutorial, we’ll discuss how to create a new JSON (JavaScript Object Notation) file in Python. JSON is a lightweight data-interchange format that is easy for humans to read and write and easy for machines to parse and generate.
It is used to store information in an organized, easy-to-access manner. It gives us a readable collection of data that can be accessed in a logical manner.
Step 1: Install Required Python Library
All Python installations come with the built-in json module, so no extra installation is required. This module provides a way for Python to encode and decode the JSON data.
Step 2: Create a Python Dictionary
To create a JSON file in Python, we need to start with a dictionary that can contain key-value pairs. So, the first step is to create the Python Dictionary.
1 2 3 4 5 |
dictionary = { "name": "John", "age": 30, "city": "New York" } |
Step 3: Convert Python Dictionary to JSON
We use the json.dumps() function to convert the Python dictionary into a JSON string. Let’s convert the dictionary we created earlier:
1 2 3 |
import json json_data = json.dumps(dictionary) |
Step 4: Write the JSON data to a file
Finally, we can write the JSON string to a file using the write() function. Here is how to do it:
1 2 |
with open('output.json', 'w') as json_file: json_file.write(json_data) |
Full Python Code
1 2 3 4 5 6 7 8 9 10 11 12 |
import json dictionary = { "name": "John", "age": 30, "city": "New York" } json_data = json.dumps(dictionary) with open('output.json', 'w') as json_file: json_file.write(json_data) |
Output File
Here is our resulting JSON file:
{ "name": "John", "age": 30, "city": "New York" }
Conclusion
And that’s it! You have successfully created a new JSON file in Python. The JSON file is easy for humans to read and for machines to parse and generate.
This can be particularly useful in various scenarios such as storing data, generating configuration files, and much more.
For more advanced manipulation of JSON files, the Python documentation provides a wealth of information and methods available in the json module.