How to write JSON to file

Posted in Python by Dirk - last update: Feb 02, 2024

To save a JSON to a file in Python, use json.dump (data, file_object) where data is the JSON-like object, and file_object is the opened file in write mode.

What is JSON

JSON, or JavaScript Object Notation, 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 often used to transmit data between a server and a web application, as well as for configuration files and data storage.

JSON is a text format that consists of key-value pairs, where keys are strings and values can be strings, numbers, objects, arrays, booleans, or null. The basic structure looks like this:

{
  "name": "John Doe",
  "age": 25,
  "city": "New York",
  "isStudent": false,
  "grades": [90, 85, 92]
}

JSON and Python

In Python, a similar format for representing data is called a dictionary. Python dictionaries have a syntax that is quite similar to JSON. Here’s the equivalent Python representation of the above JSON:

data = {
    "name": "John Doe",
    "age": 25,
    "city": "New York",
    "isStudent": False,
    "grades": [90, 85, 92]
}

Save JSON to file

To write JSON to a file in Python, you can use the built-in json module

Here’s an example:

import json

# Your data (dictionary)
data = {
    "name": "John Doe",
    "age": 25,
    "city": "New York",
    "isStudent": False,
    "grades": [90, 85, 92]
}

# Specify the file path
file_path = "example.json"

# Open the file in write mode
with open(file_path, 'w') as file:
    # Write the JSON data to the file
    json.dump(data, file)

print(f"Data has been written to {file_path}")

In this example, json.dump() is used to write the Python dictionary (data) to a JSON file specified by the file_path. The file is opened in write mode (w), and the with statement ensures that the file is properly closed after writing.

After running this code, you’ll find a file named example.json in the same directory as your script, containing the JSON data.

Other articles