- How to Create JSON file in Python
- How to create a JSON file
- Creating JSON file in Python IDLE
- The result of the python script
- How to Convert a String to JSON in Python
- What Is a JSON File?
- Working with JSON Files in Python
- From JSON to Python Object: Deserializing
- From Python Object to JSON String: Serializing
- Creating a JSON File with dump()
- Printing in the Command Line
- Learn More About JSON and Python
- How to Create a JSON File in Python
- Example
- Creating a json file from the existing json file in Python
- Example
How to Create JSON file in Python
Here’s a sample Python logic to create a JSON file. JSON’s purpose is to exchange data between applications.
How to create a JSON file
Here is the logic. In the data object, you can find the JSON information.
data = < 'value1': 1, 'value2': 2, 'a_dict_of_values' : < 'd1': 'hello', 'd2': 'world' >, 'value3': 1.234 > with open('data.json', 'w', encoding='utf-8') as f: json.dump(data, f, ensure_ascii=False, indent=4)
JSON is a key/value structure similar to a Python dictionary. The With Open statement opens the file and assigns it to the object f.
The output file is data.json, and the mode is W, which is write mode. The format encoding=’utf-8′ tells data how it writes to the output file.
The JSON.dump writes data to the output file. The four arguments are VIZ: data, f, ensure_ascii, and indent=4. The indent=4 writes data to output in a readable format.
The ensure_ascii value according to python docs: If ensure_ascii is true (the default), the output is guaranteed to have all incoming non-ASCII characters escaped. If ensure_ascii is false, these characters will be output as-is.
Creating JSON file in Python IDLE
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.
The result of the python script
After you run the script, an output file of data.json will create and it has all the formatted JSON data.
How to Convert a String to JSON in Python
JSON stands for JavaScript Object Notation. Although its name indicates that it is associated with the JavaScript programming language, the JSON format is language-independent and frequently used in many different programming languages.
What Is a JSON File?
JSON files are commonly used in transferring data between computers. For instance, when downloading a file from an API, you often need to deal with JSON files. Here is a great article that explains downloading a file in Python from an API.
The following is an example of a JSON file:
Files that store data in JSON format are called JSON files. These files are text-based, human-readable, and easy to process – all of which make them highly popular.
In this article, we will learn how to convert a string to JSON in Python and how to create JSON files from Python objects.
Working with JSON Files in Python
Python has a built-in library called json which provides simple and efficient methods for working with JSON files. Let’s go over some examples that demonstrate how to convert a string to JSON in Python and vice versa.
From JSON to Python Object: Deserializing
The following is a JSON string:
We can use the loads() method of the json library to convert this string to a Python object:
>>> import json >>> myobject = json.loads(example)
We have just converted JSON encoded data into a Python object. This process is called deserializing. The resulting Python object is a dictionary. A Python dictionary consists of key-value pairs and we can easily access its items using the keys. For example, if we want to access the FirstName in the myobject dictionary, we write:
If we have a JSON file and want to turn it into a Python object, we can use the load() method. Take a quick look at the “employee” JSON file at the beginning of the article. The following code block reads this file and saves it into a Python dictionary.
>>> with open("employee.json", "r") as read_file: . employee = json.load(read_file) . >>> print(employee) , ]>
Now employee is a Python dictionary object.
It is important to emphasize the difference between the json library’s load( ) and loads() methods. The load method is used for creating a Python object from a JSON file, whereas the loads() method converts a JSON string to a Python object.
From Python Object to JSON String: Serializing
Just like we can create a Python object from a JSON file, we can convert a Python object to a JSON string or file. This process is called serialization.
The dumps() method converts a Python dictionary to a JSON string. In the deserializing section, we created a dictionary called myobject . It can be converted back to a JSON string as follows:
The output is a string (notice the single quotes around the curly brackets), so we cannot access a specific key-value pair as we do with dictionaries.
This very simple string is not difficult to read. However, JSON strings can be much longer and have nested parts. For such cases, the dumps() method provides a more readable way of printing. We can pretty print this string by setting the optional indent parameter:
>>> print(json.dumps(myobject, indent=3))
The dumps() method also has a parameter for sorting by key:
>>> print(json.dumps(myobject, indent=3, sort_keys=True))
JSON files are often used for serialization (pickling), e.g. for when you want to maintain some data between the runs of your application. You can learn more about object serialization in this article.
Creating a JSON File with dump()
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. The method for performing this task is dump() .
Let’s use the dump() method for creating a JSON file. We’ll use the employee dictionary we created in the previous section:
with open("new_employee.json", "w") as write_file: json.dump(employee, write_file, indent=4)
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.
The dump() method takes two positional arguments. 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.
Printing in the Command Line
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.
The first step is to open a command-line interface. Then we need to change the directory to the location where the new_employee.json file is saved.
The following command will print the JSON file in a nice, clean format:
python -m json.tool new_employee.json
The following image shows how it looks in the Windows command prompt.
Learn More About JSON and Python
We have covered how to read and write JSON files in Python. The built-in json library makes it easy to do both of these. One of the advantages of Python is the rich selection of built-in and third-party libraries that simplify most tasks.
If you are learning or plan to learn Python, our Learn Programming with Python track is a great way to start. It is designed for beginners and contains 5 interactive courses. The advantage of learning with an interactive course is that you get real, hands-on practice writing code; this is essential for learning a programming language.
LearnPython.com also offers an entire course dedicated to JSON Files in Python. The course is also interactive and contains 35 exercises. If you want to practice the concepts we’ve discussed in this article, this course is for you. Happy learning!
How to Create a JSON File in Python
To create a json file in Python, you can use the “with open()” expression. The “open()” function takes the file name and mode as an argument. If the file doesn’t exist, it will be created. The “with statement” is recommended for working with files because it assures that open file descriptors are closed automatically after program execution leaves the context of the with statement.
Example
import json with open('new_file.json', 'w') as f: print("The json file is created")
We are trying to open a file called new_file.json with w mode in this code. However, the file does not exist in the file system, creating a new file in the same folder.
Creating a json file from the existing json file in Python
To create a json file from an existing json file in Python, you can use the “open()” and with statement in write mode and dump the json data into a new json file.
Example
"data": [ "color": "red", "value": "#f00" >, "color": "green", "value": "#0f0" >, "color": "blue", "value": "#00f" >, "color": "black", "value": "#000" > ] >
Now, we will create a new json file from this data.json file.
import json with open('data.json') as f: data = json.load(f) with open('new_file.json', 'w') as f: json.dump(data, f, indent=2) print("New json file is created from data.json file")
New json file is created from data.json file
So basically, we are reading the existing json file, creating a new json file, and dumping the content to this new file.