Explain Codes LogoExplain Codes Logo

How do I write JSON data to a file?

python
json
serialization
exception-handling
Anton ShumikhinbyAnton Shumikhin·Aug 20, 2024
TLDR

To save JSON data to a file in Python, employ the json.dump() function:

import json data = {"key": "value"} # Consider this as your JSON equivalent to "Hello, World!" with open('data.json', 'w', encoding='utf-8') as file: json.dump(data, file, ensure_ascii=False, indent=4)

There you have it! This piece of code writes your data into data.json using 'utf-8' encoding, keeps Unicode symbols intact, presents JSON in a readable format, and neatly closes the file.

Simplifying complex data serialization

You might find yourself with more complex data structures, leading to a TypeError. Fear not, here's how to personalize your serialization:

from json import JSONEncoder class MyEncoder(JSONEncoder): def default(self, obj): # Customize your logic here, once done, save it as a snippet for future JSON battles! return super().default(obj) with open('data.json', 'w', encoding='utf-8') as file: json.dump(data, file, cls=MyEncoder, ensure_ascii=False, indent=4)

Python 2 adjustments, for the nostalgic ones

Those good old times, when Python 2 held our hand to greatness. Here's how to write JSON files in Python 2, with our dear friend io.open(). Don't forget to convert JSON data into Unicode:

import io import json data = {"key": "value"} # Or {"hello": "world"} if you feel like a programmer today with io.open('data.json', 'w', encoding='utf-8') as file: file.write(unicode(json.dumps(data, ensure_ascii=False, indent=4)))

Preserving fair order and space just like your favorite superhero

To keep your dictionary in perfect order, resembling your comic book shelf, and to minimize the space they take up (so you have more room for other cool stuff), use the sort_keys and separators tricks:

json.dump(data, file, ensure_ascii=False, indent=4, sort_keys=True, separators=(',', ':'))

Simplify, simplify, simplify ─ Thoreau, probably

No one likes lengthy operations repeatedly. When you want simplicity and elegance, get the mighty mpu to help you out:

import mpu data = {"key": "value"} # Or your favorite line from Thoreau mpu.io.write('data.json', data)

Plan B: Exception handling at your service

Equipping your code with try/except can save the day by preventing crashes when you least expect them:

try: with open('data.json', 'w', encoding='utf-8') as file: json.dump(data, file, ensure_ascii=False, indent=4) except IOError as e: print('An error occurred:', e) # Bazinga! Caught you, little bug!

Power move: Advanced serialization techniques

Standard techniques sometimes just don't do it. In these cases, Python's json module remains your reliable alley, letting you level up your functionality:

  • Up your game by using the default parameter in json.dump().
  • Tackle complex tasks using a json.JSONEncoder subclass. You've got this!

Format matters: JSON, YAML, CSV, pickle, or?

Consider your requirements. Sometimes a simple good ol' CSV, a fancier YAML, or even a sophisticated pickle might be a better fit than JSON. And that's FINE!