Sling Academy
Home/Python/Python: Write a list of dictionaries to a JSON file

Python: Write a list of dictionaries to a JSON file

Last updated: January 02, 2024

Overview

JSON (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 based on a subset of the JavaScript language and is commonly used for transmitting data in web applications.

Lists and dictionaries are two of the most commonly used data structures in Python. A list of dictionaries is a common way to represent a collection of records or objects, where each record is a dictionary with a common set of keys.

In this tutorial, you’ll learn how to write a list of dictionaries to a JSON file in Python, enhancing data persistence and exchange in your applications.

Writing to JSON

To write a list of dictionaries to a JSON file in Python, you can use the built-in json module, which provides a simple API for encoding and decoding JSON data.

Example 1: Basic JSON Writing

import json

# Define a list of dictionaries
data = [
    {'name': 'John', 'age': 30, 'city': 'New York'},
    {'name': 'Jane', 'age': 25, 'city': 'Los Angeles'}
]

# Write the list of dictionaries to a file
with open('data.json', 'w') as f:
    json.dump(data, f)

Here, we define a simple list of dictionaries and write it to a file named data.json. We use the json.dump function, which takes two arguments: the data to be encoded and the file object to write to.

Example 2: Pretty Printing

To make the JSON output more readable, you can use the indent argument to add indentation to the output.

import json

# Write the list of dictionaries to a file with indentation
with open('data_pretty.json', 'w') as f:
    json.dump(data, f, indent=4)

Setting indent to 4 means each level in the JSON will be indented by 4 spaces. Note that this increases file size but makes it easier to read for humans.

Example 3: Working with File Path

When working with file paths, it’s crucial to ensure the path is correct and the correct permissions are in place. The pathlib module can make file handling more intuitive.

from pathlib import Path
import json

# Define the file path
json_file_path = Path('/path/to/your/folder/data.json')

# Write the list of dictionaries to a JSON file
with json_file_path.open('w') as f:
    json.dump(data, f, indent=4)

This code uses Path to define the file path, offering more flexibility for file manipulation and being compatible with various operating systems.

Handling Exceptions

Error handling with Try-Except blocks can ensure your program doesn’t crash unexpectedly during the file writing process.

import json

# Handling exceptions during the writing process
try:
    with open('data.json', 'w') as f:
        json.dump(data, f, indent=4)
except IOError as e:
    print(f'An error occurred: {e}')

By using a Try-Except block, the code catches any IOError that may be raised if the file cannot be opened or written to. This allows the program to handle the error gracefully.

Working with Different Encodings

If you’re dealing with non-standard text encodings, the json module also provides options to accommodate that.

import json

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

Here we specify 'utf-8' as the encoding and set ensure_ascii to False to allow non-ASCII characters to be written to the file. This is especially important if your data contains special characters, such as accents or symbols from non-English languages.

Summary

We’ve explored multiple ways to write a list of dictionaries to a JSON file in Python, from simple dumps to pretty-printed and correctly encoded outputs. Exception handling and working with file paths were also discussed to ensure robust and adaptable coding practices. Whether you’re storing application data or processing data for exchange between services, these techniques establish a strong foundation for working with JSON in Python.

Next Article: Python: How to Convert a List to JSON (2 Approaches)

Previous Article: How to Parse JSON Data in Python

Series: Python: Network & JSON tutorials

Python

You May Also Like

  • Python Warning: Secure coding is not enabled for restorable state
  • Python TypeError: write() argument must be str, not bytes
  • 4 ways to install Python modules on Windows without admin rights
  • Python TypeError: object of type ‘NoneType’ has no len()
  • Python: How to access command-line arguments (3 approaches)
  • Understanding ‘Never’ type in Python 3.11+ (5 examples)
  • Python: 3 Ways to Retrieve City/Country from IP Address
  • Using Type Aliases in Python: A Practical Guide (with Examples)
  • Python: Defining distinct types using NewType class
  • Using Optional Type in Python (explained with examples)
  • Python: How to Override Methods in Classes
  • Python: Define Generic Types for Lists of Nested Dictionaries
  • Python: Defining type for a list that can contain both numbers and strings
  • Using TypeGuard in Python (Python 3.10+)
  • Python: Using ‘NoReturn’ type with functions
  • Type Casting in Python: The Ultimate Guide (with Examples)
  • Python: Using type hints with class methods and properties
  • Python: Typing a function with default parameters
  • Python: Typing a function that can return multiple types