How to Save a Python Dictionary as JSON

Mateen KianiMateen Kiani
3 min read

How to Save a Python Dictionary as JSON

Working with Python dicts often means you need to save them for later. JSON is a universal text format that many systems accept. But how do you turn your dict into JSON and write it to a file without fuss?

In this article, we'll walk you through the built-in json module, show you how to dump a dict to a file, handle errors, and keep your code clean and readable.

Using the json module

The json module is part of Python's standard library. It gives you two main functions: dump and dumps. Use dumps to get a JSON string from a dict. Use dump to write that string directly to a file.

import json

data = {'name': 'Alice', 'age': 30, 'tags': ['developer', 'python']}
json_string = json.dumps(data)
print(json_string)

Tip: Use dumps when you need the JSON data in memory. Use dump when you want to write directly to a file.

Saving a dict to a file

To save your dict, open a file in write mode and use json.dump. This writes a compact JSON string to disk.

import json

data = {'a': 1, 'b': 2}

with open('data.json', 'w') as f:
    json.dump(data, f)

For more details on handling files, see our guide on writing JSON to file in Python.

Pretty printing

By default, dump writes all data on one line. You can add indent and sort_keys to make it more readable.

import json

data = {'b': 2, 'a': 1}

with open('data.json', 'w') as f:
    json.dump(data, f, indent=4, sort_keys=True)

This will create a file that looks clean when you open it.

Handling errors

Working with I/O can fail. Wrap your code in try/except to catch common issues.

import json

try:
    with open('data.json', 'w') as f:
        json.dump({'x': 1}, f)
except IOError as e:
    print('File error:', e)
except TypeError as e:
    print('Type error:', e)

Tip: A TypeError often means your dict has non-serializable objects. Convert them or use a custom encoder.

Loading JSON back

To read your JSON file as a Python dict, use json.load.

import json

with open('data.json', 'r') as f:
    data = json.load(f)

print(type(data), data)

Common pitfalls

  • Forgetting to open the file in the right mode.
  • Using non-serializable objects in your dict.
  • Overwriting important data by accident.

By following these steps, you can save and retrieve dict data safely. For a deeper look at converting dicts to JSON strings, check our json stringify guide.

Conclusion

Saving a Python dict as JSON is simple thanks to the built-in json module. Choose dump for files and dumps for strings. Handle errors and format your output. With this in your toolbox, you can move data between services, store settings, or log information in a standard, portable format.

0
Subscribe to my newsletter

Read articles from Mateen Kiani directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Mateen Kiani
Mateen Kiani