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 in Python

JSON (JavaScript Object Notation) is a lightweight data format used to exchange data between applications. In Python, JSON data is very similar to dictionaries. Here’s a step-by-step example to create a JSON file.

Sample Python Logic

import json

# Define the data to be written to JSON
data = {
    'value1': 1,
    'value2': 2,
    'a_dict_of_values': {
        'd1': 'hello',
        'd2': 'world'
    },
    'value3': 1.234
}

# Write data to a JSON file
with open('data.json', 'w', encoding='utf-8') as f:
    json.dump(data, f, ensure_ascii=False, indent=4)

Explanation

  1. Data Structure
    The data object is a Python dictionary containing key/value pairs. Nested dictionaries are allowed, just like JSON objects.
  2. Opening the File with open('data.json', 'w', encoding='utf-8') as f:
    • 'data.json' is the output file.
    • 'w' mode opens the file for writing.
    • encoding='utf-8' ensures proper encoding of characters.
    • with open automatically closes the file after writing.
  3. Writing JSON Data json.dump(data, f, ensure_ascii=False, indent=4)
    • data: the Python dictionary to write.
    • f: the file object.
    • ensure_ascii=False: outputs non-ASCII characters as-is instead of escaping them.
    • indent=4: formats the JSON in a human-readable way with 4 spaces per indentation level.

Output

The resulting data.json will look like this:

{
    "value1": 1,
    "value2": 2,
    "a_dict_of_values": {
        "d1": "hello",
        "d2": "world"
    },
    "value3": 1.234
}

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.

Import json package
Python logic to create a JSON file

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.

Python JSON file
Output from the python script

Reference books