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.

Reference books
- Practical Web Scrapping Examples With Python
- Python Data Science with Pandas: Master 12 Advanced Projects
Related posts
You must be logged in to post a comment.